简体   繁体   中英

How do I handle transaction errors?

Imagine I have the following code inside a HTTP request handler:

// these come from the HTTP request payload.
var channel = {};
var screencast ={};

try {
  connection.beginTransaction(function(err) {
    if (err) { 
      throw err; 
    }
    connection.query('INSERT INTO Channels SET ?', channel, function (err, result) {
      if (err) { 
        connection.rollback(function() {
          throw err;
        });
      }
      connection.query('INSERT INTO Screencasts SET ?', screencast, function (err, result) {
        if (err) { 
          connection.rollback(function() {
            throw err;
          });
        }
        connection.commit(function(err) {
          if (err) { 
            connection.rollback(function() {
              throw err;
            });
          }
          console.log('success!');
        });
      });
    });
  });
} catch (err) {
  // render error page or something like that.
  console.log(err)
}

When an error occurs, I expect the catch block to be invoked - this is not the case. Why not?

I do not see the point of throwing so many errors if I cannot catch them. Can someone please explain?

Also, if I cannot rely on the catch block, how do I detect that an error occurred and then do something ?

(I know so little about this code because I adapted an example .)

Spent some time learning about promises !

var mysql   = require('mysql');
var Promise = require('bluebird');
Promise.promisifyAll(require('mysql/lib/Connection').prototype);

connection.beginTransactionAsync().then(function() {
  return connection.queryAsync('INSERT INTO Channels SET ?', channel);
}).then(function() {
  return connection.queryAsync('INSERT INTO Screencasts1 SET ?', screencast);
}).then(function() {
  return connection.commit();
}).error(function(e) {
  connection.rollback();
});

When you are dealing with error-first asynchronous callbacks, errors are not thrown. Errors are instead passed as the first parameter of the callback functions. So handle the errors there. (In the case of nested callbacks, that can mean simply calling the parent callback with the error.)

Basically: You can not throw errors inside of these callbacks unless they are caught inside the same callback in which it is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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