How to specify HTTP error code using Express.js?
Asked Answered
S

13

257

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.

Seljuk answered 12/5, 2012 at 12:17 Comment(3)
My answer to a related question could help: #10171357Gaullism
Could you please update the accepted response?Mythical
Does this answer your question? How to programmatically send a 404 response with Express/Node?Unvalued
M
425

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');
Mythical answered 30/4, 2014 at 17:19 Comment(8)
+1 for using the latest version of the API. If you want to send more down the wire, just chain: res.status(400).json({ error: 'message' })Billington
What about if I don't have a response variable? In a mongoose validation I have to rise an error done(new Error('My error text'))Drawl
@Drawl if you don't have a response variable, then you can't sent a response.Mythical
This is all deprecated now, you should use res.sendStatus(401);.Leatrice
This response would be a lot more complete if it ended with res.send('Then you shall die').Rountree
@Leatrice Do you have a source for that? The documentation doesn't indicate .status() is deprecated. .sendStatus() is just a shorthand for .status(code).send(codeName) where the codeName is the standard HTTP response text for the given code.Dippold
@JamesCoyle My comment was related for a relevant version of Express for year 2017.Leatrice
I was surprised that res.status(400).json(new Error('message')) did not work. The result was an empty JSON object {}. Instead, use TyMayn's comment of res.status(400).json({ error: 'message' })Melyndamem
P
120

A simple one liner;

res.status(404).send("Oh uh, something went wrong");
Pustulant answered 16/2, 2015 at 18:18 Comment(0)
E
46

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);
Eisinger answered 24/9, 2017 at 11:38 Comment(3)
great solution but this gives me UnhandledPromiseRejectionWarning error. How to make sure the errors are handled in our error middlewareIdola
async/await is not supported out of the box by express, try this github.com/fastify/fastifyEisinger
throw works only if the route is synchronous. If it's an async route, you have to manually call next(). I suppose (but haven't tried) you could just pass the same object you show in throw but to next().Bathe
B
21

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')
Begotten answered 21/2, 2017 at 14:27 Comment(0)
P
19

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

Peace answered 12/5, 2012 at 13:42 Comment(2)
But I want the error code to be sent to eventHandler middleware, so express's custom error page be displayed.Seljuk
For anyone reading this in 2016: As per Express 4.x, res.send(404) is deprecated. It's now res.sendStatus(404). expressjs.com/en/api.html#res.sendStatusKuenlun
S
13

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);
}
Spermogonium answered 11/11, 2014 at 15:0 Comment(0)
B
11

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.

Beckett answered 10/8, 2012 at 2:2 Comment(0)
C
11

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);
Campuzano answered 24/8, 2019 at 17:53 Comment(0)
W
9

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'));
Wattle answered 24/9, 2013 at 15:25 Comment(2)
What is does next do?Civic
next is calling next handler which in express.js usually are trying to render error pages.Yokoyama
S
8

Express deprecated res.send(body, status).

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

Spindling answered 24/12, 2017 at 12:34 Comment(1)
Thanks. Wokring with warning of middlewares.Metamer
A
2

If you want to send the status code without its string representation you can do:

res.status(200).send();
Antedate answered 23/2, 2023 at 11:19 Comment(0)
K
0

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

Koosis answered 25/6, 2018 at 23:41 Comment(0)
O
0

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();
Oculus answered 3/9, 2021 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.