我正在尝试找出完美的方法来处理我的应用程序中的错误。我设计了一种方法(见下文),但我对丢失原始错误的事实感到困扰。
在我的代码中,我有这样的东西(这是一个中间件):
exports.tokenApi = function( req, res, next, token ){
Workspace = mongoose.model('Workspace');
User = mongoose.model('User');
req.application = {};
// Find the token
Workspace.findOne({ 'access.token': token } , function(err, doc){
if(err){
next( new g.errors.BadError503('Database error resolving workspace Id') );
} else {
if(! doc ){
next( new g.errors.ForbiddenError403('Access denied') );
} else {
// The token is there and it's valid.
// Set req.application.workspaceId, req.application.login and
// req.application.workspace (which contains all of the settings!)
req.application.workspaceId = doc._id;
req.application.workspace = doc;
req.application.login = doc.access.filter(function(entry){ return entry.token == token; } )[0].login;
next();
}
}
一个不同的文件定义了错误:
// Defining the BadError error type, thrown by the application itself
//
function BadError503( message ){
this.httpError = 503;
this.message = message || "Internal error";
this.name = this.constructor.name;
}
util.inherits(BadError503, Error);
exports.errors.BadError503 = BadError503;
// Defining the Error error type, thrown by the application itself
//
function ForbiddenError403( message ){
this.httpError = 403;
this.message = message || "User not logged in";
this.name = this.constructor.name;
}
util.inherits(ForbiddenError403, Error);
exports.errors.ForbiddenError403 = ForbiddenError403;
该应用程序定义了一个错误处理程序,如下所示:
exports.AppErrorHandler = function( err, req, res, next){
var user = null;
var workspace = null;
switch(err.name){
case 'BadError503':
case 'ForbiddenError403':
Logger(null, null, 4, 'The application threw an error: ' + err.name + ', message: ' + err.message, req );
res.json( { message: err.message }, err.httpError );
break;
这段代码的问题是我丢失了原始错误。我有一个自定义错误处理程序,可以说“做正确的事”(参见上面的代码:通过 Ajax 返回错误),但如果我以某种方式保留实际问题的原因,我希望它。
这给我带来了一个不同的问题:这是不好的做法吗?在某种程度上,我喜欢我自己抛出错误并且可以 100% 处理它的事实(我自己编写了 Error 对象)。但是,丢失原始错误对我来说似乎是个坏主意。
我也许可以将原始错误传递给我创建的自定义错误对象。但是还是...
有什么想法吗?或者,我应该注意的任何标准模式?