Expressjs - Handling Errors With Middleware Expressjs - Handling Errors With Middleware express express

Expressjs - Handling Errors With Middleware


Instead manually creating error, you can delegate that error like below.

return next(err);

And your error will go deep down all the routes defined until it find routes with below signature.

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

You can see the err argument in above route.

Ideally you can use below two methods for both DEVELOPMENT & PRODUCTION environment.

if (process.env.NODE_ENV === 'development') {    app.use(function (err, req, res, next) {        res.status(err.status || 500);        logger.log('info', err.message + " expected URL was " + req.url);        res.status(err.status).send(err.status, {            message: err.message,            error  : err        });    });}app.use(function (err, req, res, next) {    res.status(err.status || 500);    logger.log('error', err.message + " expected URL was " + req.url);    res.status(err.status).send(err.status, {        message: err.message,        error  : {}    });});

You can capture actual populated error object in there.


You should create your own Error type that allows you to provide all the information necessary to act on the error.

var util = require('util');function HttpError(message, statusCode){    this.message = message;    this.statusCode = statusCode;    this.stack = (new Error()).stack;}util.inherits(Error, HttpError);module.exports = HttpError;

Then include your new error object in your code and use it like

next(new HttpError('Not Found', 404));

Or you could go crazy and implement an error type for each response code pre-populating the statusCode part.

Ref: What's a good way to extend Error in JavaScript?