我想集中在這樣的錯誤響應創建:
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:當然,你可以創建一個對象來extend the standard error這樣的:
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);
我對相關問題的回答可能有所幫助:http://stackoverflow.com/questions/10170857/can-i-reuse-the-express-js-錯誤視圖/ 10556093#10556093 – Pickels
您能否更新接受的回覆? –