How to specify HTTP error code?

2019-01-16 15:19发布

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.

10条回答
放荡不羁爱自由
2楼-- · 2019-01-16 15:45

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

查看更多
3楼-- · 2019-01-16 15:52

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);
查看更多
一夜七次
4楼-- · 2019-01-16 15:54

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.

查看更多
等我变得足够好
5楼-- · 2019-01-16 15:57

express deprecated res.send(body, status). Use res.status(status).send(body) instead

查看更多
地球回转人心会变
6楼-- · 2019-01-16 16:03

A simple one liner;

res.status(404).send("Oh uh, something went wrong");
查看更多
淡お忘
7楼-- · 2019-01-16 16:03

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'));
查看更多
登录 后发表回答