If I define error handling middleware with express like so:
app.use(function(err,req,res,next){
// Do Stuff
});
How do I get the HTTP status code of the error(or do I just assume is's a 500)?
Thanks,
Ari
If I define error handling middleware with express like so:
app.use(function(err,req,res,next){
// Do Stuff
});
How do I get the HTTP status code of the error(or do I just assume is's a 500)?
Thanks,
Ari
In short, your code has to decide the appropriate error code based on the specific error you are handling within your error handling middleware.
There is not necessarily an HTTP status code generated at this point. By convention, when I call
next(error)
from a middleware function or router handler function, I put acode
property so my error handling middleware can dores.status(err.code || 500).render('error_page', error);
or something along those lines. But it's up to you whether you want to use this approach for your common 404 errors or only 5XX server errors or whatever. Very few things in express itself or most middleware will provide an http status code when passing an error to thenext
callback.For a concrete example, let's say someone tried to register a user account in my app with an email address that I found already registered in the database, I might do
return next(new AlreadyRegistered());
where the AlreadyRegistered constructor function would put athis.code = 409; //Conflict
property on the error instance so the error handling middleware would send that 409 status code. (Whether it's better to use error handling middleware vs just dealing with this during the normal routing chain for this "normal operating conditions" error is arguable in terms of design, but hopefully this example is illustrative nonetheless).FYI I also recommend the httperrors npm module which provides nicely-named wrapper classes with a
statusCode
property. I have used this to good effect in a few projects.You could try to define the status code in the route:
Then: