1

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Yeah it's just that I have a million of such functions and want to find a way to catch them all
0
  • 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.