Consider this TypeScript code snippet:
app.get('/test_feature', function (req: Request, res: Response) {
throw new Error("This is the bug");
});
app.use(logErrors);
function logErrors (err: Error, req: Request, res: Response, next: NextFunction) {
console.log(err);
mongoDal.log(err.message, err);
next(err);
}
In the above code, when an error is thrown in a request handler, it triggers the logErrors function as expected.
However, if we modify the code to include an async function:
app.get('/test_feature', async function (req: Request, res: Response) {
throw new Error("This is the bug");
await someAsyncFunction();
});
Since the function is now asynchronous, the error is caught by Express's default error handler, bypassing both the custom error handler and Node's default error handler:
process.on('uncaughtException', function (err: Error) {
try {
console.log(err);
mongoDal.log(err.message, err);
} catch (err) {
}
});
How can we ensure that the 'logErrors' function is called when an error occurs within an async function? Is there a generic solution without having to wrap every async function in a try/catch block?