【发布时间】:2015-12-23 19:50:32
【问题描述】:
背景
假设我正在使用 NodeJS + Express。我在 Express 中注册了某些错误处理程序,它们会以适当的方式处理我的应用程序中可能出现的所有错误。
因此,每当我需要这样做时,我都会在我的应用程序中抛出错误。如果有一个未处理的错误,我让它传播,直到它到达一个错误处理程序。但是,在尝试在 Promise 链中抛出错误时,我遇到了一个问题。举个例子:
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;
});
}
虽然我一直期待我重新抛出的错误最终至少会命中通用错误处理程序,但我却看到我发送到我的应用程序的请求挂起,并且我正在使用的 promise 库抱怨Unhandled rejection。
问题
很简单,我想知道如何解决这样一个事实,即我似乎错误地处理了我通过在我的承诺链中抛出一个错误而创建的拒绝。
编辑:为了澄清(具体而言)错误处理程序和controller 函数是什么,请参阅下面的 cmets。
【问题讨论】:
-
您期望它命中的“通用错误处理程序”是什么?如果
controller是一条路线,您应该使用第三个next参数并执行next(error) -
我想你明白我在做什么——
next(error)听起来是正确的答案 -
如果你展示你是如何调用
controller()的,我们会更好地了解你在做什么以及哪些选项最有意义。 -
如果
app是一个 Express 应用程序,通用错误处理程序将简单地类似于app.use(function(err, req, res, next) { ... })。controller函数是路由的处理程序,例如/。 -
您希望哪个通用错误处理程序受到重新抛出的错误的影响?没有 - 除了抱怨未处理的拒绝的那个。
标签: javascript express promise bluebird