我使用next 参数作为catch 回调(又名errback)
将任何未处理的拒绝转发到表达错误处理程序:
app.get('/foo', function (req, res, next) {
somePromise
.then(function (result) {
res.send(result);
})
.catch(next); // <----- NOTICE!
}
或更短的形式:
app.get('/foo', function (req, res, next) {
somePromise
.then(function (result) {
res.send(result);
}, next); // <----- NOTICE!
}
然后我们可以发出有意义的错误响应
在 express 错误处理程序中使用 err 参数。
例如,
app.use(function (err, req, res, /*unused*/ next) {
// bookshelf.js model not found error
if (err.name === 'CustomError' && err.message === 'EmptyResponse') {
return res.status(404).send('Not Found');
}
// ... more error cases...
return res.status(500).send('Unknown Error');
});
恕我直言,全球 unhandledRejection 事件不是最终答案。
比如这样容易出现内存泄漏:
app.use(function (req, res, next) {
process.on('unhandledRejection', function(reason, p) {
console.log("Unhandled Rejection:", reason.stack);
res.status(500).send('Unknown Error');
//or next(reason);
});
});
但这太重了:
app.use(function (req, res, next) {
var l = process.once('unhandledRejection', function(reason, p) {
console.log("Unhandled Rejection:", reason.stack);
res.status(500).send('Unknown Error');
//next(reason);
});
next();
process.removeEventLister('unhandledRejection', l);
});
恕我直言,expressjs 需要对 Promise 提供更好的支持。