我试过:

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

但是总会出现一个500的错误代码。


当前回答

表达已弃用的res.send(body, status)。

使用res.status(status).send(body)或res.sendStatus(status)代替

其他回答

我想以这种方式集中创建错误响应:

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

所以我总是有相同的错误输出格式。

PS:当然你可以创建一个对象来扩展标准错误,就像这样:

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

根据Express (Version 4+)文档,您可以使用:

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

简单的一行;

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

表达已弃用的res.send(body, status)。

使用res.status(status).send(body)或res.sendStatus(status)代替

在特快4.0中,他们做对了:)

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