在我目前的项目中,我看到了一些奇怪的代码结构,看起来像这样:
async_api_call_with_throw_errors //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.catch((e) => {
Sentry.captureException(e)
if (e?.validateError) {
//some actions
} else {
dispatch({ type: errorOccurred, errorText: e?.message, fatalError: false })
}
})
.catch(e => {
Sentry.captureException(e)
dispatch({ type: errorOccurred, errorText: e, fatalError: false })
})如果" catch“块捕获了几种错误类型,这是可以的,但是在"then”块之后有两个具有相同错误的"catch“块有意义吗?
我不这么认为。但是也许我不知道关于try...catch的一些重要的事情?
发布于 2020-10-26 14:56:21
如果前面的catch抛出一个错误,然后由随后的catch捕获,则可以使用多个catch。看一下下面的代码。
const promise1 = new Promise((resolve, reject) => {
throw 'Uh-oh!';
});
promise1.catch((error) => {
console.error(error);
throw "Error was caught!"
}).catch(err => {
console.error(err)
})
// Expect Output:
// > Uh-oh!
// > Error was caught!希望这能消除一些疑问。
发布于 2020-10-26 14:55:49
捕获并不都是为了同样的尝试。最后一个陷阱是try块。但第一个陷阱是promise链。
try {
-------
.catch(e => {
Sentry.captureException(e)
dispatch({ type: errorOccurred, errorText: e, fatalError: false })
})承诺的区块是,
async_api_call_with_throw_errors //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.catch((e) => {
const eventId = Sentry.captureException(e)
if (e?.validateError) {
//some actions
} else {
dispatch({ type: errorOccurred, errorText: e?.message, fatalError: false })
}
})现在,我们不应该对这样的异步调用使用try/catch。如果你想在异步操作周围使用try/catch块,你应该使用await来调用async方法,并且应该没有promise解析链。代码应该写成,
try {
await async_api_call_with_throw_errors;
await async_api_call_with_throw_errors;
await async_api_call_with_throw_errors;
.....
} catch (error) {
handle errors
}顺便说一句,你应该确保你想要使用的异步/等待函数也是一个异步函数。
发布于 2020-10-26 14:57:17
如果第一个catch抛出一个错误,它应该可以工作,尽管我不确定为什么有人会这样做。
https://stackoverflow.com/questions/64532506
复制相似问题