Adding the keyword async
to a function seems to require catching errors within that function. However, there are situations where it doesn't make sense to catch errors and defer them to the caller instead, especially when the context of the function call is unknown (e.g., whether the caller will use res.json(e) or next(e), or neither).
Is there a way to work around this constraint? Is it possible to still use the async
keyword for asynchronous operations inside the function and delegate error handling to the caller?
Here's a contrived example to illustrate the issue:
try {
function example(obj = {}) {
try {
obj.test = async () => {
throw new Error('example error')
}
return obj
} catch (e) {
console.log('example outer error')
}
}
let doit = example()
doit.test()
} catch (e) {
console.log('outer error')
}
The above script results in an Uncaught Exception
. Removing the async
keyword allows it to work, although async may be necessary for other functionality.
Why can't the error be caught when calling doit.test()
?
While normally I would adapt and adjust as needed, I found myself unable to answer this question when explaining it to someone else. Can you shed some light on this matter?