[英]Javascript async catch errors at caller
如果我将关键字async
添加到函数中,似乎我必须捕获该函数中的错误。 有时捕获错误没有任何意义,我想将它们推迟给调用者,因为我可能不知道调用该函数的上下文(例如,调用者在执行res.json(e)或next(e),或两者都不
有没有解决的办法? 因此,我可以使用async
(以便在函数内部await
) 并将错误延迟给调用方?
这是一个真正的例子
https://codepen.io/anon/pen/OzEXwM?editors=1012
try { function example(obj = {}) { try { obj.test = async () => { // if I remove async keyword, it works, otherwise I'm forced to catch errors here //try{ throw new Error('example error') // I know `example outer error` won't catch as the returned object loses the context //}catch(e){ // console.log('I do not want to catch error here'), I wan't to defer it to the caller //} } return obj } catch (e) { console.log('example outer error') } } let doit = example() doit.test() // why doesn't 'outer error' catch this? } catch (e) { console.log('outer error') }
脚本按原样运行将给出Uncaught Exception
。 但是,如果我删除了async
关键字,它就会起作用(是的,我知道在此示例中,异步很愚蠢,这只是一个示例)
为什么在doit.test()
时无法捕获错误?
通常,我只会遵从并进行重做,但是今天早晨我试图向其他人解释时,我才真正知道答案。
为什么在调用doit.test()时无法捕获错误?
因为它是异步的。 在到达抛出错误部分时,外部的try catch块已被执行并传递。 可以这么说。
要解决此问题,由于async和await只是Promises的语法糖,您只需使用catch回调即可 。 您的test()
函数将返回一个Promise,因此只需在返回的Promise上添加一个回调
doit.test().catch(()=>{
console.log('Any uncaught exceptions will be sent to here now');
});
演示版
function example(obj = {}) { obj.test = async() => { throw new Error('example error') } return obj; } let doit = example() doit.test().catch(e => { console.log('Caught an exception: ', e.message); });
如果要捕获test()函数的错误。 您需要await doit.test()
https://jsfiddle.net/1tgqvwof/
我将您的代码包装在一个匿名函数中,因为等待必须在异步函数中
(async function () {
try {
async function example(obj = {}) {
try {
obj.test = async () => { // if I remove async keyword, it works, otherwise I'm forced to catch errors here
//try{
throw new Error('example error') // I know `example outer error` won't catch as the returned object loses the context
//}catch(e){
// console.log('I do not want to catch error here'), I wan't to defer it to the caller
//}
}
return obj
} catch (e) {
console.log('example outer error')
}
}
let doit = example()
await doit.test() // why doesn't 'outer error' catch this?
} catch (e) {
console.log('outer error')
}
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.