0

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 ?
  });
}
2
  • Why your 500 and 503 function have not the same signature as the 404 one ? Commented Feb 13, 2019 at 10:26
  • Why use try-catch blocks and when something results in a 500 or 503 throw new Error("internal service error") respond with response.status(500) or (503) in your routes. Also, what happens when you swap out the first status code with 500 or 503? Is it just running 404 because it's first? Commented Feb 13, 2019 at 10:31

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

It works with next(error), but I'm not able to get the error message in my controller. See edit.
Error handlers are executed after middlewares and controllers, so next() in an error handler calls express' default error handler
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.