Home > Software design >  What is the first argument of next() in express js?
What is the first argument of next() in express js?

Time:10-05

It seems you can pass an argument to next(), usually an error?

How is this used? How do I access that error?

eg:

router.get('/my-url', function(req, res, next) {
  next(new Error('my error');
});

CodePudding user response:

If you pass an error to next(), if will forward it to the error handler.

An error handler is a middleware defined with 4 inputs, where first input is an error.

So, you need to define an error handler in order to catch the error that is passed with next():

// Error handler
app.use((error, req, res, next) =>

  console.log('ERROR:', error)

);
  • Related