Angular noob
Angular noob

Reputation: 437

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

Upvotes: 2

Views: 838

Answers (2)

Trott
Trott

Reputation: 70085

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.

Upvotes: 0

Angular noob
Angular noob

Reputation: 437

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

Upvotes: 1

Related Questions