简体   繁体   English

Node JS + Express应用程序中的错误处理

[英]Error handling in Node JS + Express application

I am writing a small web-app using Node JS (version 8.4.0), Express (version 4.15.3) and using Passport (version 0.3.2) for authentication. 我正在编写一个使用Node JS(版本8.4.0),Express(版本4.15.3)和Passport(版本0.3.2)进行身份验证的小型Web应用程序。

I am using PostgreSQL 9.6 for database. 我正在使用PostgreSQL 9.6作为数据库。

I am not able to understand how to handle errors using Promises in my application. 我无法理解如何在应用程序中使用Promises处理错误。

I have divided my app into routes (has information related to which routes to handle via http requests), views (handlebars templates to render pages) and model (functions related to database queries). 我已将我的应用程序划分为路由(具有与通过http请求处理的路由有关的信息),视图(用于呈现页面的车把模板)和模型(与数据库查询相关的功能)。

Here is an example code from a model: 这是来自模型的示例代码:

var helpers = require('./helpers'); //Has a function to perform db queries

exports.getCustomerDetails = (cust_id,cb)=>{

    var qs = 'select * FROM customers WHERE cust_id=($1)';
    var params = [cust_id];

    helpers.dbquery(qs,params,(error,results)=>{

        if(error){
            return cb(error);
        }

        return cb(null,results);

    });

}

At present, what I am doing in the corresponding route handler is to send HTTP 500 as response. 目前,我在相应的路由处理程序中所做的就是发送HTTP 500作为响应。

//Get Customer details based on cust_code as input

router.get('/getCustomerDetails',(req,res,next)=> {
    if (req.user) {

      var cust_code = req.query.value;

      db.getCustomerDetails(cust_code, (error, result) => {

        if (error) {
          res.sendStatus(500);
        }
        res.status(200).send(result);
      });
    } else {
      res.sendStatus(401);
    }
})

I want to understand what is the best way to handle errors at both levels, ie route and database. 我想了解在两个级别(即路由和数据库)上处理错误的最佳方法是什么。

I read a few articles on error handling and searched Stackoverflow, but I am not able to wrap my head around it being a beginner in any sort of development. 我阅读了一些有关错误处理的文章,并搜索了Stackoverflow,但是我无法以任何开发的初学者的身份来思考它。

Please suggest how to handle errors in my web-app and any references which could help me understand error handling in web-apps. 请提出如何处理我的网络应用程序中的错误以及任何可以帮助我了解网络应用程序中的错误处理的参考。

The following could do what you ask for. 以下可以满足您的要求。 Create a promise, catch the reject of that promise and return the promise you created but not with the catch so the caller can catch the reject again. 创建一个promise,捕获该promise的拒绝并返回您创建的promise,但不要使用catch,以便调用方可以再次捕获拒绝。

var helpers = require('./helpers'); //Has a function to perform db queries

exports.getCustomerDetails = (cust_id, cb) => {
  var qs = 'select * FROM customers WHERE cust_id=($1)';
  var params = [cust_id];
  //create a promise
  const p = new Promise(
    (resolve,reject) =>
      helpers.dbquery(qs, params, (error, results) =>
        (error)
          ? reject(error)
          : resolve(results)
      )
  );
  //catch the reject
  p.catch(
    error => {
      //... do something with the error on the db level
    }
  );
  //return the promise that DID NOT have the error caught
  return p;
};


router.get('/getCustomerDetails',(req,res,next)=> {
  if (req.user) {
    var cust_code = req.query.value;
    //getCustomerDetails returns a promise
    db.getCustomerDetails(cust_code)
    .then(
      result =>
        res.status(200).send(result)
    )
    .catch(
      error =>
      res.sendStatus(500)
    )
  } else {
    res.sendStatus(401);
  }
});

From my point of view the best way is to handle all errors in routes layer, in order to format them properly according to the interface. 以我的观点,最好的方法是处理路由层中的所有错误,以便根据接口正确格式化它们。 Imagine in the future you change your REST API layer by a GraphQL layer, with this approach you just have to modify this layer, and not the rest. 想象一下,将来您将通过GraphQL层更改REST API层,使用这种方法,您只需要修改该层,而不必修改其余的层。 The way to throw all errors from other layers: I usually create an Error object and add several custom properties, for example: 从其他层抛出所有错误的方式:我通常创建一个Error对象并添加几个自定义属性,例如:

var error = Error();
error.code = 401;
error.log = true;
error. translate = true;
error.message = "Unauthorized";
....
throw error;

And in the routes layer, you can catch the error and create the custom response with all the data. 在路由层中,您可以捕获错误并使用所有数据创建自定义响应。 It is flexible and powerful. 它是灵活而强大的。

Hope it helps. 希望能帮助到你。

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

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