213

我试过了:

app.get('/', function(req, res, next) {
    var e = new Error('error message');
    e.status = 400;
    next(e);
});

和:

app.get('/', function(req, res, next) {
    res.statusCode = 400;
    var e = new Error('error message');
    next(e);
});

但总是会宣布错误代码 500。

4

12 回答 12

366

根据 Express(版本 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');
于 2014-04-30T17:19:51.927 回答
98

一个简单的班轮;

res.status(404).send("Oh uh, something went wrong");
于 2015-02-16T18:18:47.313 回答
32

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

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);
于 2017-09-24T11:38:17.473 回答
19

你可以res.send('OMG :(', 404);只使用res.send(404);

于 2012-05-12T13:42:15.183 回答
16

在 express 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')
于 2017-02-21T14:27:37.763 回答
12

从我在 Express 4.0 中看到的情况来看,这对我有用。这是需要身份验证的中间件的示例。

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);
}
于 2014-11-11T15:00:17.267 回答
11

errorHandler 中间件的版本与 express 的某些(可能是旧的?)版本捆绑在一起似乎具有硬编码的状态代码。此处记录的版本:http://www.senchalabs.org/connect/errorHandler.html另一方面,您可以做您想做的事情。因此,也许尝试升级到最新版本的 express/connect。

于 2012-08-10T02:02:28.767 回答
9

老问题,但仍然出现在谷歌上。在当前版本的 Express (3.4.0) 中,您可以在调用 next(err) 之前更改 res.statusCode:

res.statusCode = 404;
next(new Error('File not found'));
于 2013-09-24T15:25:47.857 回答
8

我试过

res.status(400);
res.send('message');

..但它给了我错误

(节点:208)UnhandledPromiseRejectionWarning:错误:发送后无法设置标头。

这对我有用

res.status(400).send(yourMessage);
于 2019-08-24T17:53:20.030 回答
3

快递已弃用res.send(body, status)

res.status(status).send(body)改为使用

于 2017-12-24T12:34:32.400 回答
0

我建议使用Boom包处理发送 http 错误代码。

于 2018-06-25T23:41:26.337 回答
0

异步方式:

  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();
于 2021-09-03T00:05:31.347 回答