Ashu Ashu - 9 days ago 5
Javascript Question

Choosing a HTML status code for errors in Express apps

In my API if any query fails then what should be the response status code?

Example :

Grade.find({},function(err,grades) {
if (err)
res.status(500).json({error:err,message: 'Somthing went wrong please try again later'});


Is 500 OK or should it be something else ?


TL;DR A 500 status is the closest thing to a 'one size fits all' error, but you can get into much deeper details.

According to the standards, you have plenty of choices :

5xx Server Error

500 Internal Server Error

501 Not Implemented

502 Bad Gateway

503 Service Unavailable

504 Gateway Timeout

510 Not Extended

You could also create your own 5xx status to differentiate between error types, just try to use numbers that are not defined for anything else.

Or stick to a 500 status and attach the original error code to your result :

res.status(500).json({error:err, code : err.code, message: 'Somthing went wrong please try again later'});

However, before answering with 5xx, you want to make sure that the error doesn't come from the client, by validating the data you receive. If the received data is invalid, use a 400 Bad Request code. If the issue is security related, use a 403 Not Authorized, etc...