Express.js error handling function for async functions

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

Upvotes: 1

Views: 680

Answers (3)

Matt
Matt

Reputation: 74680

Try Koa as it's already async.

Otherwise, create a generic wrapper function that 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.

Upvotes: 2

Bhavin Verma
Bhavin Verma

Reputation: 45

  • you must use try and catch block.
import express, {NextFunction, Request, Response} from "express";

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

const app = express();


app.get('/', async (req, res, next){
   try{ 
    await fails();
    }
    catch(err){
      //you can also create a global function to handle errors
      return res.send(err) 
   }
});

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

Upvotes: 0

Lucjan Grzesik
Lucjan Grzesik

Reputation: 779

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

Upvotes: 0

Related Questions