HTTP response codes are not magic numbers; this is a specification. The descriptive text is just a useful reminder, but the protocol itself relies on these status codes, and the main ones are very valuable. Two thoughts. You can create a constant at the top of the file and do the following:
var REQUEST_ENTITY_TOO_LARGE = 413; response.status(REQUEST_ENTITY_TOO_LARGE);
However, most REST APIs simply implement the following answers:
200 - OK 201 - Created
Finally, if it is useful, I will share our code for creating custom error pages:
module.exports = function(app) { app.use(function(req, res) { // curl https://localhost:4000/notfound -vk // curl https://localhost:4000/notfound -vkH "Accept: application/json" res.status(404); if (req.accepts('html')) { res.render('error/404', { title:'404: Page not found', error: '404: Page not found', url: req.url }); return; } if (req.accepts('json')) { res.send({ title: '404: Page not found', error: '404: Page not found', url: req.url }); } }); app.use( function(err, req, res, next) { // curl https://localhost:4000/error/403 -vk // curl https://localhost:4000/error/403 -vkH "Accept: application/json" var statusCode = err.status || 500; var statusText = ''; var errorDetail = (process.env.NODE_ENV === 'production') ? 'Sorry about this error' : err.stack; switch (statusCode) { case 400: statusText = 'Bad Request'; break; case 401: statusText = 'Unauthorized'; break; case 403: statusText = 'Forbidden'; break; case 500: statusText = 'Internal Server Error'; break; } res.status(statusCode); if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { console.log(errorDetail); } if (req.accepts('html')) { res.render('error/500', { title: statusCode + ': ' + statusText, error: errorDetail, url: req.url }); return; } if (req.accepts('json')) { res.send({ title: statusCode + ': ' + statusText, error: errorDetail, url: req.url }); } }); };
dankohn
source share