tonymx227
tonymx227

Reputation: 5451

Handle errors with ExpressJS

I try to handle 503 and 500 errors with ExpressJS but it only works with 404 error.

My middleware :

var error = function(server) {

  // 404
  server.app.use(function(request, response) {
    response.status(404);
    response.redirect('/404');
  });

  // 500
  server.app.use(function(error, request, response, next) {
    response.status(500);
    response.redirect('/500');
    next(error);
  });

  // 503
  server.app.use(function(error, request, response, next) {
    response.status(503);
    response.redirect('/503');
    next(error);
  });
};

module.exports = error;

Function in my controller (using routes) :

function error500(request, response) {
  response.render('0-templates/' + response.locals.options.template + '/500', {
    _layoutFile: false,
    error: //how to get the error ?
  });
}

Upvotes: 0

Views: 187

Answers (2)

Shay Moshe
Shay Moshe

Reputation: 482

Not sure why you're using 3 different functions as you have only one error handler in express, you can use something like:

server.app.use((err, req, res, next) => {
  if (err.code) {
    res.status(err.code);
    console.log(err);
    return res.redirect('/'+err.code);
  } else {
    res.status(500);
    console.log(err);
    return res.redirect('/500');
  }
});

or something similar, in order to execute the error response you should call next(err) from your logic code

Sources: here and here

Upvotes: 0

Leo
Leo

Reputation: 751

You are missing the error argument for the 404 callback which leads express to believe it is a middleware and not an error handler, therefore returning 404 for every requests going through said middleware.

You should also add next argument to all error handlers.

From express documentation on error handling:

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next).

Upvotes: 1

Related Questions