node.js - Express middleware error handler -


following generated template express. in app.js there following snippet

app.use('/users', users);  // catch 404 , forward error handler app.use(function(req, res, next) {   var err = new error('not found');   err.status = 404;   next(err); });  // error handler app.use(function(err, req, res, next) {   // set locals, providing error in development   res.locals.message = err.message;   res.locals.error = req.app.get('env') === 'development' ? err : {};    // render error page   res.status(err.status || 500);   res.render('error'); }); 

per understanding, middleware run in order app.use('/users', users) 404 handler error handler. question how possible reach error handler , execute line res.status(err.status || 500); ? wont every failed request passed through 404 handler first , therefor getting status code of 404? please let me know if missing something! thank you

no, won't. if @ these event handlers declarations you'll see error handler unhandled error, has additional err parameter:

app.use(function(req, res, next) { app.use(function(err, req, res, next) { 

error-handling middleware takes 4 arguments. must provide 4 arguments identify error-handling middleware function. if don’t need use next object, must specify maintain signature. otherwise, next object interpreted regular middleware , fail handle errors. details error-handling middleware.

so, when route not found, last declared middleware calling, it's 404 error handler.

but when call next error: next(err) or code throws error, last error handler calling.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -