How to properly handle errors in Express? How to properly handle errors in Express? express express

How to properly handle errors in Express?


You'll want to check out Express Error Handling. From there:

app.param('userId', function(req, res, next, id) {    User.get(id, function(err, user) {        if (err) return next(err);        if (!user) return next(new Error('failed to find user'));        req.user = user;        next();    });});

The sweetspot that you are missing is the return next(...)


That's because you're doing it wrong: you already threw an Error (which will be processed by Express and return a 500 - Error page for the user or something like that) but you are also trying to send your own response to the client: res.send('event found!');

You should really check out the Express guide about Error Handling here: http://expressjs.com/guide/error-handling.html

What I would do in your example is:

function NotFound(msg){  this.name = 'NotFound';  Error.call(this, msg);  Error.captureStackTrace(this, arguments.callee);} app.get('/event/:id', function(req, res, next){  if (req.params.id != 1) {    throw new NotFound('Cannot find event ' + req.params.id);  } else {    res.send('event found!');  }});app.error(function(err, req, res, next){    if (err instanceof NotFound) {        res.render('404.ejs');    } else {        next(err);    }});


You have a couple of problems in your code:

  • When responding to the client, you need to use the response object (res rather than req).

  • When sending an error to next, you should return, so the rest of the function doesn't run.

Here's your code after fixing those errors:

app.get('/event/:id', function(req, res, next) {    if (req.params.id != 1) {        return next(new Error('cannot find event ' + req.params.id));    }    res.send('event found!'); // use res.send (NOT req.send)});