2017-07-30 38 views
0

我知道如何使用node.js(express)編寫簡單的API。但現在我很困惑,無法區分代碼這兩塊拋出錯誤與正常回報相比在快遞中

if(err){ return res.status(500).json(err) } 
return res.json(result) 

if(err) { throw new Error(err) } 
return res.json(result) 

什麼是一個API響應的標準?我只是返回2屬性,就像

if(err){ return res.json({ status: false, msg: 'user password is incorrect }) } 
return ({ status: true, msg: result.token }) 

我的方法有什麼問題,爲什麼我們應該使用throw?

回答

0

您通常不希望在Express中拋出一個錯誤,因爲除非它被捕獲,否則它會在不給用戶提示的情況下使進程崩潰,並且捕獲錯誤並保持請求上下文不容易除此以外。

而是在Express處理程序中的選擇應該在直接返回錯誤響應(如您的示例中)和調用next(err)之間。在我的應用程序中,我總是使用後者,因爲它可以讓我設置錯誤處理中間件來始終如一地處理各種問題。下面

例子:

app.get('/something', (req, res, next) => { 
    // whatever database call or the like 
    Something.find({ name: 'something'}, (err, thing) => { 
    // some DB error, we don't know what. 
    if (err) return next(err); 
    // No error, but thing wasn't found 
    // In this case, I've defined a NotFoundError that extends Error and has a property called statusCode set to 404. 
    if (!thing) return next(new NotFoundError('Thing was not found')); 
    return res.json(thing); 
    }); 
}); 

那麼一些中間件的錯誤處理,像這樣:

app.use((err, req, res, next) => { 
    // log the error; normally I'd use debug.js or similar, but for simplicity just console in this example 
    console.error(err); 

    // Check to see if we have already defined the status code 
    if (err.statusCode){ 
    // In production, you'd want to make sure that err.message is 'safe' for users to see, or else use a different value there 
    return res.status(err.statusCode).json({ message: err.message }); 
    } 
    return res.status(500).json({ message: 'An error has occurred, please contact the system administrator if it continues.' }); 
}); 

注意,幾乎一切都在快速通過中間件來完成。

+0

你能顯示一些代碼嗎?做下一步(err)會產生什麼樣的結果?我的大部分api都沒有中間件,下一步(err)還是相關的? –

+0

你推薦什麼中間件來處理錯誤? –

+0

我展示的那個?節點中的中間件只是一個處理函數。有時你可以通過使用模塊來實現,但是你不需要。我寫了praeter(https://www.npmjs.com/package/praeter)作爲包裝我提到的上述內容的一種方式,但您可以使用自己的代碼輕鬆完成。 – Paul