Home > database >  Express.js error handling function for async functions
Express.js error handling function for async functions

Time:08-24

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);

CodePudding user response:

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.

CodePudding user response:

You can use try-catch in you route.

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

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

const app = express();
app.get('/', async() => {
  try {
    await fails();
  } catch (error) {
    // You catch the error in here
  }

});
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.log(`err`, err);
  res.send({
    err
  })
});
app.listen(9999);

  • Related