Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch all errors in express not working

I want to server a error.ejs file for all errors that are not handled individually.

This code does not do anything when I get a duplicate key error from mongoose user.save() http://expressjs.com/guide.html#error-handling

app.js

app.use(function(err, req, res, next){
  res.status(500);
  res.render('error', { error: "Woops, we encountered an error..." });
});

routes/index.js

user.save(function(err){
    if ( err ) throw err;
});

The example below gives me this error: Caught exception: [ReferenceError: next is not defined]

user.save(function(err){
    if ( err ) next(err);
});
like image 919
chovy Avatar asked Oct 15 '25 19:10

chovy


1 Answers

Your snippet

user.save(function(err){
    if ( err ) next(err);
});

is presumably inside a route that has a function( req, res ) on it?

What you need to do is a "next" on that function

function MyRoute( req, res, next ) {
  user.save(function(err){
    if ( err ) 
      return next(err);

    // carry on here doing whatever
  });
}

app.get('/some/route', MyRoute);
like image 178
MrPurpleStreak Avatar answered Oct 18 '25 23:10

MrPurpleStreak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!