Skip to content

Instantly share code, notes, and snippets.

@therealplato
Created August 26, 2013 21:03
Show Gist options
  • Save therealplato/6346624 to your computer and use it in GitHub Desktop.
Save therealplato/6346624 to your computer and use it in GitHub Desktop.
express error handling middleware
// example based on @AriPorad Expressjs - All Routes Are 404
// http://stackoverflow.com/questions/18406591/expressjs-all-routes-are-404/18407658#18407658
// custom error handler
// put this at the end of your middleware chain and handle errors however you want
app.use(function (err, req, res, next) {
if (err.message
&& (~err.message.indexOf('not found')
|| (~err.message.indexOf('Cast to ObjectId failed')))) {
res.status(404).render('404', { url: req.originalUrl })
} else if(err){
console.error(err.stack)
res.status(500).render('500')
};
// no errors
next();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment