我试过:
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的错误代码。
从我在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);
}
我想以这种方式集中创建错误响应:
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);