186

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.

tech-man
  • 2,486
  • 2
  • 15
  • 18

11 Answers11

330

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');
Dan Mandle
  • 4,620
  • 2
  • 21
  • 24
  • 43
    +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' })` – TyMayn Sep 23 '14 at 04:15
  • 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'))` – Mikel Jun 06 '17 at 14:09
  • 1
    @Mikel if you don't have a response variable, then you can't sent a response. – Dan Mandle Jun 06 '17 at 17:32
  • 1
    This is all deprecated now, you should use `res.sendStatus(401);`. – Cipi Jun 16 '17 at 16:50
  • 1
    This response would be a lot more complete if it ended with `res.send('Then you shall die')`. – goodvibration Jun 22 '18 at 08:46
  • 1
    @Cipi 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`. – James Coyle May 20 '19 at 10:03
  • @JamesCoyle My comment was related for a relevant version of Express for year 2017. – Cipi May 22 '19 at 16:24
88

A simple one liner;

res.status(404).send("Oh uh, something went wrong");
Mike P
  • 2,277
  • 1
  • 19
  • 25
26

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);
Manuel Spigolon
  • 6,514
  • 4
  • 36
  • 57
17

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

Mustafa
  • 9,075
  • 7
  • 62
  • 109
  • But I want the error code to be sent to eventHandler middleware, so express's custom error page be displayed. – tech-man May 12 '12 at 14:05
  • 13
    For anyone reading this in 2016: As per Express 4.x, `res.send(404)` is deprecated. It's now `res.sendStatus(404)`. http://expressjs.com/en/api.html#res.sendStatus – 0xRm Jun 28 '16 at 06:35
13

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')
Steven Spungin
  • 17,551
  • 4
  • 57
  • 56
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.

catphive
  • 3,451
  • 3
  • 29
  • 27
9

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);
}
Ido Ran
  • 9,010
  • 11
  • 73
  • 129
8

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'));
webarnes
  • 101
  • 1
  • 2
4

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);
Pathik Vejani
  • 4,048
  • 6
  • 47
  • 84
Tarun Rawat
  • 156
  • 1
  • 8
3

Express deprecated res.send(body, status).

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

techytushar
  • 604
  • 5
  • 14
Rajeev Jayaswal
  • 949
  • 11
  • 20
0

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

JoeTidee
  • 17,573
  • 19
  • 82
  • 120