What is the first argument of next() in express js?

Issue

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

Solution

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)

);

Answered By – NeNaD

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published