Node.js MySQL Error Handling

后端 未结 6 1790
遇见更好的自我
遇见更好的自我 2020-12-08 22:30

I\'ve read several examples for using mysql in node.js and I have questions about the error handling.

Most examples do error handling like this (perhaps for brevity)

6条回答
  •  佛祖请我去吃肉
    2020-12-08 23:11

    I think you can do something like this. No matter how, the connection will be released once it is done querying and the server will not crash because of the error.

    var queryString = "SELECT * FROM notification_detail nd LEFT JOIN notification n ON nd.id_notification = n.uuid WHERE login_id = ?  id_company = ?;";
    var filter = [loginId, idCompany];
    
    var query = connection.query({
        sql: queryString,
        timeout: 10000,
    }, filter );
    
    query
      .on('error', function(err) {
       if (err) {
          console.log(err.code);
          // Do anything you want whenever there is an error.
          // throw err;
       } 
    })
    .on('result', function(row) {
      //Do something with your result.
    })
    .on('end', function() {
      connection.release();
    });
    

    This can be an alternative solution which is much simpler.

    var query = connection.query({
    sql: queryString, 
    timeout: 10000,
    }, function(err, rows, fields) {
        if (err) {
          //Do not throw err as it will crash the server. 
          console.log(err.code);
        } else {
          //Do anything with the query result
        } 
        connection.release()
    });
    

提交回复
热议问题