我试过:

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的错误代码。


当前回答

异步方式:

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

其他回答

从我在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);
}

简单的一行;

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

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

在特快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')

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