2016-07-22 26 views
0

我已經編寫了幾個MEAN Stack應用程序並設置了API,但是我總是在混淆處理API中的錯誤的最佳方式路線。Node/Express API路徑中錯誤處理的正確和可持續的方式

如果我解釋了錯誤或者我的思想/觀念有缺陷,請糾正我。我正在解釋我認爲是對的。只是想成爲一個更好的程序員。

當我說的錯誤,我指的是以下情況:

  1. 一般錯誤,有些東西你沒有預測已經發生了,需要處理,也許服務器宕機或者服務器過載,基本上我們無法預測可能發生的任何事情。這種類型的錯誤大多是在這裏處理的「我想」(見下面的註釋代碼):

    app.get('/user', isLoggedIn, function(req, res){ 
    
        User.find(_id, function(err, user){ 
         // HERE I am not sure how to handle this, Maybe we can't reach the DB or anything else could have happened. How do you handle this error so no matter what kind of error it is we can handle it gracefully and the app doesnt crash and we don't lose value data and the user is made aware of the issue. 
         if(err) 
    

我已經看到了不同的方式的人是如何管理的上述錯誤這裏有幾個例子:

if(err) 
    // I think this is wrong! Maybe okay for development but not for deployment 
    console.log("The Error is " + err); 

if(err) 
    // Again I think not a good way of handling error because doesn't provide the system or the front-end user with any useful data. 
    throw err; 

if(err) 
    // Not Sure 
    res.send(err); 

if(err) 
    res.json(err); 

所以上面的是,當我們無法預測什麼樣的,或者當錯誤發生時可能但也有另外一種類型見下文

  • 所以,讓我們說,我們通過上面的if(err)階段,走到else,這是我們可以預測的錯誤,因爲這是用戶交互的用武之地。例如繼續上面的例子(看到代碼評論):

    app.get('/user',isLoggedIn,function(req, res) { 
        User.find(_id, function(err, user) { 
         if (err){ 
          // NOT SURE WHAT TO DO HERE 
         } 
         // HERE lets say the user we are trying to get does not exist, now this is something we can predict, how to handle this not only gracefully so we don't crash the app but also provide the front end user with some useful information. 
         else if(!user){ 
    
         } 
         else if(user){//Do what you were meant to do!} 
        }); 
    }) 
    
  • 現在怎麼我通常管理這種類型的錯誤是發回了一些資料給前端用戶像這樣:

    return(res.json({message: "The user you are trying to find does not exist, contact the system admin please."})); 
    

    我發送回在前端一些JSON數據和顯示一個div或一個警告框等內

    小號o這些是我處理錯誤的兩種「種類」或更好的單詞「情況」。最好的方式處理它們,這樣他們的應用程序可以自己管理而不會崩潰,但也確保前端用戶知道發生了什麼,以便他們知道他們的下一步。什麼是處理API錯誤的最佳實踐。

    回答

    1

    我更喜歡使用nextcustom Error

    Next

    app.get('/user', isLoggedIn, function(req, res, next){ 
        User.find(_id, function(err, user){ 
         if (err) 
          return next(err); // Forwarding error to error-middleware 
          ...or... 
          throw new Error('Cause'); // If error is critical for app and app must be stopped 
         ... 
        }); 
    

    在錯誤的中間件,我們可以選擇多少信息發送到控制檯/用戶,以及如何目前信息

    // Detect current environment 
    if (req.app.get('env') != 'development') { 
        ...  
    } 
    
    // Detect request type 
    if (req.xhr) 
        req.json(...) 
    else 
        res.render('error.html', ...); 
    

    Custom Error

    在上面的示例中,您可以拋出AuthorizeError並將其轉發next。更多關於custom error的閱讀here。 Imho對於小型應用程序來說太過分了。