Error handling

Now, we can finally get back to the generated app.js, the 404 Error page not found, and any other errors the application might want to show to the user.

A middleware function indicates an error by passing a value to the next function call. Once Express sees an error, it will skip any remaining non-error routing, and it will only pass it to error handlers instead. An error handler function has a different signature than what we saw earlier.

In app.js, which we're examining, this is our error handler:

app.use(function(err, req, res, next) { 
  res.status(err.status || 500); 
  res.render('error', { 
    message: err.message, 
    error: {} 
  }); 
}); 

Error handler functions take four parameters, with err added to the familiar req, res, and next ...

Get Node.js Web Development - Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.