Error Handling
suggest changeBasic Error Handling
Express itself does not render an error view. The express-generator template does: it looks for an error view under /views and passes the message, status, and stack. For example:
views/error.pug
html
body
h1= message
h2= error.status
p= error.stack
Advanced Error Handling
Define your error-handling middleware functions at the very end of the middleware function stack. These have four arguments instead of three (err, req, res, next) for example:
app.js
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
//pass error to the next matching route.
next(err);
});
// handle error, print stacktrace
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
You can define several error-handling middleware functions, just as you would with regular middleware functions.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents