How to specify HTTP error code using Express.js?

node.jsExpressHttp Status-Codes

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

Per the Express (Version 4+) docs, you can use:

res.status(400);
res.send('None shall pass');

http://expressjs.com/4x/api.html#res.status

<=3.8

res.statusCode = 401;
res.send('None shall pass');

Solution 2 - node.js

A simple one liner;

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

Solution 3 - node.js

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

Solution 4 - node.js

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

Solution 5 - node.js

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

Solution 6 - node.js

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);
}

Solution 7 - node.js

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.

Solution 8 - node.js

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'));

Solution 9 - node.js

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

Solution 10 - node.js

Express deprecated res.send(body, status).

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

Solution 11 - node.js

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

Solution 12 - node.js

Async way:

  myNodeJs.processAsync(pays)
        .then((result) => {
            myLog.logger.info('API 200 OK');
            res.statusCode = 200;
            res.json(result);
            myLog.logger.response(result);
        })
        .fail((error) => {
            if (error instanceof myTypes.types.MyError) {
                log.logger.info(`My Custom Error:${error.toString()}`);
                res.statusCode = 400;
                res.json(error);
            } else {
                log.logger.error(error);
                res.statusCode = 500;
                // it seems standard errors do not go properly into json by themselves
                res.json({
                    name: error.name,
                    message: error.message
                });
            }
            log.logger.response(error);
        })
        .done();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontech-manView Question on Stackoverflow
Solution 1 - node.jsDan MandleView Answer on Stackoverflow
Solution 2 - node.jsMike PView Answer on Stackoverflow
Solution 3 - node.jsManuel SpigolonView Answer on Stackoverflow
Solution 4 - node.jsMustafaView Answer on Stackoverflow
Solution 5 - node.jsSteven SpunginView Answer on Stackoverflow
Solution 6 - node.jsIdo RanView Answer on Stackoverflow
Solution 7 - node.jscatphiveView Answer on Stackoverflow
Solution 8 - node.jswebarnesView Answer on Stackoverflow
Solution 9 - node.jsTarun RawatView Answer on Stackoverflow
Solution 10 - node.jsRajeev JayaswalView Answer on Stackoverflow
Solution 11 - node.jsJoeTideeView Answer on Stackoverflow
Solution 12 - node.jsMr.BView Answer on Stackoverflow