【问题标题】:Proper & Sustainable way of Error Handling in Node/Express API RoutesNode/Express API 路由中正确且可持续的错误处理方式
【发布时间】:2016-07-22 17:49:29
【问题描述】:

我已经编写了一些 MEAN Stack 应用程序并设置了 API,但对于处理 API 路由中错误的最佳方法,我总是有些困惑。

如果我解释有误或我的想法/概念有缺陷,请纠正我。我在解释我认为是对的。只是想成为一个更好的程序员。

当我说错误时,我指的是以下情况:

  1. 一般错误,您没有预料到的事情已经发生并且需要处理,可能是服务器已关闭或服务器过载,基本上是我们无法预测的任何可能发生的事情。这种类型的错误大多在这里“我认为”处理(请参阅下面的代码中的 cmets):

    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);

所以上面是当我们无法预测可能发生哪种错误或何时发生错误但还有另一种类型见下文

  1. 假设我们通过了上述if(err) 阶段并进入else,这是我们可以预测错误的地方,因为这是用户交互发挥作用的地方。例如继续上面的例子(见代码中的 cmets):

    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 或警报框等内。

所以这是我处理的错误的两种“种类”或更好的词“情况”。与他们打交道的最佳方式是什么,这样他们的应用程序可以在不崩溃的情况下自行管理,同时确保前端用户知道发生了什么,以便他们知道下一步。以及处理 API 错误的最佳做法是什么。

【问题讨论】:

    标签: javascript node.js mongodb express error-handling


    【解决方案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。恕我直言,这对于小型应用来说太过分了。

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多