How to handle 404 and 500 errors on ExpressJS

Maybe you are wondering how to handle 400 and 500 errors on ExpressJS or just doubt about it. It's quite easy, let's see:

Handling 404 and 500 errors on ExpressJS

First of all, you should handle them at the end of your routing endpoints.

How to handle 404

At the end of your routing endpoints, add:

// Route not found (404)
app.use(function(req, res, next) {
  return res.status(404).send({ message: 'Route'+req.url+' Not found.' });
});

How to handle 500

Similar but with 4 parameters and the first is the error object:

// Any error
app.use(function(err, req, res, next) {
  return res.status(500).send({ error: err });
});

All together

// [...]
// Your routing

// 404
app.use(function(req, res, next) {
  return res.status(404).send({ message: 'Route'+req.url+' Not found.' });
});

// 500 - Any server error
app.use(function(err, req, res, next) {
  return res.status(500).send({ error: err });
});

Also you can render nice pages instead of text messages or even response only with text if it's an AJAX request. 🤖

Leave a comment with your questions, doubts or experiences! 👋

David Burgos

Read more posts by this author.