Search code examples
javascriptmysqlnode.jsnode-mysql

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.)


Solution

  • 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();
    });