背景的允許傳播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