我不是第一个 express.js 应用程序,尽管我仍然需要找出处理错误的最可靠的方法。
由于 io.js 是几个月前的现实,我正在使用本机 Promises 来帮助自己处理异步性,以下代码反映了这一点。
我的错误处理中间件如下:
router.use(function (err, req, res, next) {
// in case err.custom is present, means is an "handled" Error, created by developers
if (!!err.custom) {
return res.status(err.code).json(err.message);
}
if (err instanceof Error) {
console.error(err.stack);
return res.status(500).send('Runtime Error'); // should be reported!
}
// last but not least, validation error
res.status(400).send(err);
});
一个示例控制器是这样编写的:
function callService1 (param1) {
return new Promise(function (resolve, reject) {
service.call(param1, function (err, data) {
if (!!err) return reject(err); // this is an Error object?? not sure!
if (!!data.handledError) { // this is an handled Error to the user, not 500
return reject({ custom: true, status: 403, message: 'service1 tells you that myCoolParam is not valid' });
}
resolve(data);
});
};
}
function callService2 (dataFromParam1) {
return new Promise(function (resolve, reject) {
// something here
});
}
// this is the API "controller"
module.exports = function (req, res, next) {
callService1(req.body.myCoolParam)
.then(callService2)
.then(function (service2Output) {
res.status(200).json({ message: 'everything went smooth!' });
})
.catch(next); // here is the catch-all errors
};
如您所见,express 中间件看起来非常整洁和优雅。
我通常在 中处理所有有趣的错误给用户rejects()
,其中一些是用我告诉错误处理中间件的对象调用的。
示例中的问题是service
第 3 方库。这些库有时会返回一个字符串,有时会返回一个对象(来自外部 API),有时会返回一个 javascript 错误。
目前我无法处理自定义 javascript 对象,此外,如果我想向用户抛出错误 500,我必须这样做,reject(new Error(err));
但有时这err
是一个对象,导致:
Error: [object Object]
at errorHandler (awesomeapi\postsomething.js:123:16)
at IncomingMessage.<anonymous> (node_modules\mandrill-api\mandrill.js:83:24)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:163:7)
at _stream_readable.js:891:16
at process._tickCallback (node.js:337:11)
这一点都不酷,我真的很想找到一种方法来优雅地处理这些错误,而无需添加代码(如果可能的话),因为我发现这种语法非常优雅和简洁。