Let's suppose I want to use an async function foo from an external library, which calls another async function bar that throws an error that foo does not handle:
// External library code (non-modifiable)
async function bar(){
throw Error("Error example");
}
async function foo() {
bar(); // <-- Note this is not awaited!!
}
If in my code I want to use foo, is there any way I can handle the error thrown by bar? This does not work, as foo does not await for bar:
// My code
async function myMain(){
try {
await foo();
} catch (error) {
console.log("Error captured in myMain:", error.message);
}
}
My bet is that the foo function not awaiting bar it's a bug in the external library. But until it's fixed, do I have any way to handle the error that it throws?
The code is inside an AWS Lambda, which causes 500 errors when it has unhandled exceptions. I need a way to handle the errors "gracefully" to avoid that.
I do not know why the external library calls the function that throws the error without properly handling it. But as I am forced to use it and I cannot modify its code, I think that using undhandledRejection may be the only course of action. Although I do not like it. I want to handle that function's specific unhandled errors, but let the other ones pass, as they might be bugs in my code I would like to detect.
fooasync and why do you await it? The external library seems to contain multiple bugs.foorepresents a function of an external library that does multiple things. But, because of a bug I guess, it does not always handle all the errors that can happen.bar()returns a promise that's discarded and rejected. I would call this a bug in the external library.foofunction not awaitingbaris a bug in the external library." - yes, absolutely. Make them fix it. There are some workarounds, but none of them good.