[node.js] How to specify HTTP error code?

I have tried:

app.get('/', function(req, res, next) {
    var e = new Error('error message');
    e.status = 400;
    next(e);
});

and:

app.get('/', function(req, res, next) {
    res.statusCode = 400;
    var e = new Error('error message');
    next(e);
});

but always an error code of 500 is announced.

This question is related to node.js express http-status-codes

The answer is


I would recommend handling the sending of http error codes by using the Boom package.


A simple one liner;

res.status(404).send("Oh uh, something went wrong");

I tried

res.status(400);
res.send('message');

..but it was giving me error:

(node:208) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.

This work for me

res.status(400).send(yourMessage);

Old question, but still coming up on Google. In the current version of Express (3.4.0), you can alter res.statusCode before calling next(err):

res.statusCode = 404;
next(new Error('File not found'));

You can use res.send('OMG :(', 404); just res.send(404);


Express deprecated res.send(body, status).

Use res.status(status).send(body) instead


The version of the errorHandler middleware bundled with some (perhaps older?) versions of express seems to have the status code hardcoded. The version documented here: http://www.senchalabs.org/connect/errorHandler.html on the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.


I'd like to centralize the creation of the error response in this way:

app.get('/test', function(req, res){
  throw {status: 500, message: 'detailed message'};
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500).json({status: err.status, message: err.message})
});

So I have always the same error output format.

PS: of course you could create an object to extend the standard error like this:

const AppError = require('./lib/app-error');
app.get('/test', function(req, res){
  throw new AppError('Detail Message', 500)
});

'use strict';

module.exports = function AppError(message, httpStatus) {
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message;
  this.status = httpStatus;
};

require('util').inherits(module.exports, Error);

From what I saw in Express 4.0 this works for me. This is example of authentication required middleware.

function apiDemandLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    console.log('isAuth', req.isAuthenticated(), req.user);
    if (req.isAuthenticated())
        return next();

    // If not return 401 response which means unauthroized.
    var err = new Error();
    err.status = 401;
    next(err);
}

In express 4.0 they got it right :)

res.sendStatus(statusCode)
// Sets the response HTTP status code to statusCode and send its string representation as the response body.

res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')

//If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.

res.sendStatus(2000); // equivalent to res.status(2000).send('2000')

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to http-status-codes

Laravel - Return json along with http status code Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>" HTTP status code 0 - Error Domain=NSURLErrorDomain? 400 vs 422 response to POST of data Python Request Post with param data HTTP Get with 204 No Content: Is that normal Throw HttpResponseException or return Request.CreateErrorResponse? Returning http status code from Web Api controller How to specify HTTP error code? How to get HTTP response code for a URL in Java?