2016-06-10 81 views
2

我有一個路由,首先需要查詢數據庫,然後與結果,查詢另一個Web服務,然後用該結果呈現頁面。 我有這個流程解決了,並試圖找出錯誤處理。鑑於我與多種服務交談,我試圖在返回它們表達前按摩錯誤。expressJS承諾和錯誤處理

下面是路由的代碼的結構:

Models.Episode.findById(request.params.episodeID) 
    .catch(function (error) { 
     throw (throwjs.notFound()); 
    }) 
    .then(function (episode) { 
     if (episode.getUser().id !== request.user.href) { 
      return next(throwjs.unauthorized("You do not have access to this podcast")); 
     } 
     return doSomeOtherAsyncStuff(); 
    }) 
    .then(function (queryResponse) { 
     renderPage(); 
    }) 
    .catch(function (error) { 
     next(error); 
    }); 

我的問題是用第一擋。我在這個問題上的目標是重新包裝錯誤並停止執行併發送錯誤來表達中間件。

通過上面的寫法,執行停止,但我的快速錯誤處理程序不會被調用。

我試圖重寫第一擋爲

.catch(function(error){ 
    return next(error); 
}) 

但是,這並不解決問題。我發現的唯一解決方案是將捕捉到底。但是,然後我失去了失敗的位置的背景。

任何線索我做錯了什麼? 感謝,奧利弗

+0

你是否真的重寫了第一個catch,就像你在例子中做的那樣?因爲有一個錯字。 – Seth

+0

@Seth好的一點,我重試只是爲了確認輸入錯誤並得到同樣的問題。 – otusweb

+0

@ t.niese通過在線程的早期捕獲,我知道唯一失敗的是上面的語句。如果我僅在底部添加捕獲物,那麼我不確定是什麼失敗了 – otusweb

回答

2

我建議採用不同的方法,這樣您就不必依賴長時間運行的承諾鏈。通過以下方法,您已將授權和驗證分離爲單獨的中間件,因爲它們不一定是實際情節處理程序本身的關注點。此外,這種方法更具語言表達能力。

一個額外的好處是,你可以自由地將錯誤傳遞給錯誤處理程序,以便進一步將錯誤與路由處理程序分離。

function validateEpisode(req, res, next) { 
    Models.Episode 
    .findById(req.params.episodeID) 
    .then(function(episode) { 
     req.yourApp.episode = episode; 
     next() // everything's good 
    }) 
    .catch(function(error) { 
     // would be better to pass error in next 
     // so you can have a general error handler 
     // do something with the actual error 
     next(throwjs.notFound()); 
    }); 
} 

function authUserByEpisode(req, res, next) { 
    if (req.yourApp.episode.getUser().id !== req.user.href) { 
    next(throwjs.unauthorized("You do not have access to this podcast")); 
    } 

    next(); // authorized 
} 

function episodeController(req, res) { 
    // do something with req.yourApp.episode 
} 

app.get('/episode/:id', validateEpisode, authUserByEpisode, episodeController) 
+0

有趣。我必須對此進行試驗。我對整個Express的事情還是比較新的。謝謝! – otusweb

0

嘛畢竟這是關係到throwjs框架我使用和我使用不當的事實

throw (throwjs.notFound()); 

應該

throw (new throwjs.notFound()); 

..