捕获从顶层嵌套异步函数引发的错误



我遇到麻烦"抓";使用try/catch或.catch语句的错误,我相信这是因为错误没有在";传统的";方式在顶层,我调用了异步函数中的一个函数:

async function main() {
let computedValue;
try {
computedValue = await module.doComputation();
} catch (err) {
console.log("We caught the error!")
computedValue = null;
}
}
// in `module`
import $ from 'jquery';
export function doComputation() {
return new Promise((resolve) => {
$.ajax({
type: 'GET',
url: location.href,
success: (data) => {
const text = $($.parseHTML(data)).find('#some-dom-element').text()
const total = text.match(/[+-]?d+(.d+)?/g)[0]; // this line throws an error!
if (total > 0) {
resolve(total);
}
},
error: () => {
resolve(-1);
},
});
});
}

当我运行此程序时,从doComputation内引发的异常将不被处理,看起来如下:Uncaught TypeError: Cannot read properties of null (reading '0')

我对这个函数抛出错误并不感到特别惊讶(我理解为什么(,但我需要确保main能够安全地捕捉到这个函数抛出的错误。

重要的是,我真的更希望能够在main级别捕捉到这个错误(从技术上讲,我的项目中有数百种不同的doComputation实现,必须修改所有这些实现会有点困难(。

有人知道我该如何解决这个问题吗?在await module.doComputation中添加.catch似乎并没有起到什么作用,而且还会让我的LSP不高兴。

我尝试在有问题的行中添加一个.catch语句,并将整个语句包装在try/catch中,但没有成功。

您应该在承诺中包含一个reject变量,并以的方式处理错误

return new Promise((resolve,reject) => {
$.ajax({
type: 'GET',
url: location.href,
success: (data) => {
const text = $($.parseHTML(data)).find('#some-dom-element').text()
const total = text.match(/[+-]?d+(.d+)?/g)[0]; // this line throws an error!
if (total > 0) {
resolve(total);
}
},
error: () => {
reject(-1)
},
});
});
}

并且在主中

function main() {
let computedValue;
module.doComputation().then((res) => {
computedValue = res
}).catch(()=>{
console.log("We caught the error!")
computedValue = null;
})
}

希望这能有所帮助!

最新更新