Home > OS >  Error middleware in express nodejs, next() does not catch error
Error middleware in express nodejs, next() does not catch error

Time:05-20

Why does this approach not work? How can I create an error gaurd middleware for my API?

export function ErrorCatcherMiddleware() {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      next();
    } catch (err) {
      console.log("trying request failed")
      next(err);
    }
  }  ...
  app.use(ErrorCatcherMiddleware());
  // ...routes and other middlewares
}

CodePudding user response:

The error handling middleware takes 4 arguments (error as first arg) as opposed to 3 arguments for regular middleware.

const handleErrors = (err, req, res, next) => {
    return res.status(500).json({
        status: 'error',
        message: err.message
    })

}

app.use(handleErrors)

CodePudding user response:

I may assume that it doesn't catch errors because the code that produces them is asynchronous.

To catch these errors you need to wait until the async operation is finished and in case of error call the next(err) function.

For example

app.get('/', (req, res, next) => {
  fs.readFile('/file-does-not-exist', (err, data) => {
    if (err) {
      next(err) // Pass errors to Express.
    } else {
      res.send(data)
    }
  })
})

app.use((err, req, res, next) => {
  // this middleware should be executed in case of the error
});

Or you can use middlewares that return promises like below (starting with Express 5).

app.get('/', async (req, res, next) => { // callback is "async"
  const data = await fs.readFile('/file-does-not-exist');
  res.send(data);
});

app.use((err, req, res, next) => {
  // this middleware should be executed in case of the error
});

In this case, if fs.readFile throws an error or rejects, next will be called with either the thrown error or the rejected value automatically. You can find more details about that in this document

  • Related