2016-07-22 68 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对于小型应用程序来说太过分了。