繁体   English   中英

节点/ Express API路由中正确且可持续的错误处理方式

[英]Proper & Sustainable way of Error Handling in Node/Express API Routes

我已经编写了一些MEAN Stack应用程序并设置了API,但对于如何处理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);

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

  1. 因此,可以说我们通过了上述if(err)阶段,然后转到else ,这是我们可以预测错误的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或警报框等内部的前端。

因此,这就是我要处理的两种“错误”或更好的“错误情况”。 与他们打交道的最佳方法是什么,以便他们可以在不崩溃的情况下管理自己的应用,还可以确保前端用户知道发生了什么事情,从而使他们知道下一步。 以及处理API错误的最佳实践是什么。

我更喜欢使用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更多信息,请custom error 此处 恕我直言,这对于小型应用程序来说太过分了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM