javascript - Node/Express API 路由中正确且可持续的错误处理方式

标签 javascript node.js mongodb express error-handling

我已经编写了一些 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);

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

  • 所以可以说我们通过了上面的 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 或警报框等内。

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

    最佳答案

    我更喜欢使用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', ...);
    

    自定义错误

    在上面的示例中,您可以抛出 AuthorizeError 并通过 next 转发它。有关自定义错误的更多信息,请阅读 here 。恕我直言,这对于小型应用程序来说太过分了。

    关于javascript - Node/Express API 路由中正确且可持续的错误处理方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38520973/

    相关文章:

    javascript - 如何比较数组中的元素 (javascript)

    javascript - 使用 Hammerjs、CSS-Transform 和 Transform origin 进行手势移动

    mysql - 错误 1452 MySQL 和 NodeJS。为什么数据库不能正确引用我的表?

    mongodb - 服务器选择在 10000 毫秒后超时 - 无法将 Compass 连接到本地主机上的 mongoDB

    android - 从基于移动或浏览器的应用程序连接 MongoDB

    javascript - 为什么 native 浏览器排序功能比快速排序慢?

    javascript - 对于通用 JS 和 React,是否有 '@font-face' 的替代方案

    javascript - NodeJS path.resolve 无法按预期工作

    node.js - 非socket.io 进程的示例是什么?

    mongodb - MongoDB 中的文档是什么?