How to specify HTTP error code?


Question

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.

1
136
4/1/2016 10:21:55 AM

Accepted Answer

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');
251
10/14/2014 10:05:11 PM

A simple one liner;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon