背景的允许传播JS承诺:错误
比方说,我与+的NodeJS工作快。我在Express中注册了一些错误处理程序,它将以适当的方式处理我的应用程序中可能出现的所有错误。
因此,我可以把我的应用程序错误时,我必须这样做。如果有未处理的错误,我让它传播,直到它到达一个错误处理程序。然而,在尝试在承诺链内部抛出错误时,我遇到了一个问题。看看下面的例子:
function find() {
// consider this to be a promise from a library such as Bluebird
return new Promise(function (resolve, reject) {
// ... logic ...
});
}
function controller (req, res) {
// ... omitted ...
find().then(function (result)) {
if (result) {
// let 'res' be the Express response object
res.send("It exists!");
} else {
// let SpecificError be a prototypical subclass of Error
throw new SpecificError("Couldn't find it.");
}
}).catch(function (error) {
// throw the error again, so that the error handler can finish
// the job
throw error;
});
}
虽然我一直在期待,我再扔最终至少击中一般错误处理程序中的错误,我也看不到我发送给我的应用程序挂起的请求,以及我正在使用的承诺库抱怨Unhandled rejection
。
问题
很简单,我想知道怎么解决,我似乎是处理不当,我在我的诺言链抛出一个错误创建拒绝的事实。
编辑:为澄清什么(具体)的错误处理程序和controller
功能的,看下面的评论。
什么是你期望它命中的“通用错误处理程序”?如果'controller'是一个路由,你应该使用第三个'next'参数并执行'next(error)' – loganfsmyth
我想你会看到我想要做的事情 - 'next(error)'听起来像是正确的回答 – nmagerko
如果你显示你如何调用controller(),我们会更好地了解你在做什么以及哪些选项最有意义。 – jfriend00