Express.js error handling function for async functions

Issue

How do I make express.js handle ERR_UNHANDLED_REJECTION in async route handlers? For example, how do I make it so that the code below doesn’t crash on request:

import express, {NextFunction, Request, Response} from "express";

async function fails() {
    throw `Test`;
}

const app = express();
app.get('/', async () => {
    await fails();
});
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
    console.log(`err`, err);
    res.send({err})
});
app.listen(9999);

Solution

Try Koa as it’s already async.

Otherwise, create a generic wrapper function can turn an async function into the required express response.

import express, {NextFunction, Request, Response} from "express";

function genHandler(responseHandler: Function) {
  return async function theHandler(req: Request, res: Response, next: NextFunction) {
    try {
      const res = await responseHandler(req, res, next)
      res.send(res)
    }
    catch (error) {
      next(error)
    }
  }
}

async function ok() {
    return 'ok'
}
async function fails() {
    throw `Test`;
}

const app = express();
app.get('/', genHandler(fails));
app.get('/ok', genHandler(ok));
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
    console.log(`err`, err);
    res.send({err})
});
app.listen(9999);

The handler generator can hide a lot of repeated async request/response complexity, like express middleware does for the non async world.

Answered By – Matt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published