Express error handling and async await Express error handling and async await express express

Express error handling and async await


There is another process.on event you can set up a listener for - unhandledRejection.

You can use it to handle those rejections all over the code.

NOTE: remember to terminate your process after you logged everything you needed. More on this here.


I've found a solution:

app.get('/foo', async function (req: Request, res: Response, next: NextFunction) {    dontAwait(() => bar());});async function dontAwait(func: () => void) {   try {       await func();   }   catch (err) {     logErrors(err);   }}


I still have one case in which I can't catch the errors.

You could, but you currently simply don't do anything with the result. If you want your usual error handlers to trigger, you need to await it.

It happens when I call an async function without the await keyword

I can't see any good reason for that. But if you really want to fire and forget the function, you can do it. You just have to handle errors explicitly:

bar().catch(e => logger.err(e));