numtel / meteor-mysql

Reactive MySQL for Meteor
MIT License
343 stars 41 forks source link

Returning error to client #73

Closed chriscarpenter12 closed 8 years ago

chriscarpenter12 commented 8 years ago

Usually when writing methods if there's an error I will do something like this:

Meteor.methods({
  toggleMaintenance: function(data) {
    if (data) {
      Queue.upsert({_id: 'maintenance_mode'}, {},
        function(err) {
          if (err) {
            throw new Meteor.Error('Error', err);
          }
        });
    } 
  }
});

and on the client side Meteor.call() get the error message and return it to the client. When doing this same technique:

Meteor.methods({
  'updateCompany': function(gid) {
    liveDb.db.query(
      'SELECT * FROM table WHERE id = ?',
      [gid],
      function(error, rows) {
        if (error) {
          throw new Meteor.Error('sql-update', error);
        }
      }
    );
  }
});

It is throwing an error and causing the server to crash. I was looking at Meteor.wrapAsync() but can't seem to get that to work. Anyone have any ideas on this?

chriscarpenter12 commented 8 years ago

Just for clarity of others that may come across this as well. I figured it out and this is working for me. There may be a more elegant solution...

Meteor.methods({
  'deleteCompany': function(gid) {
    var query = Meteor.wrapAsync(liveDb.db.query, liveDb.db);
    try {
      var result = query('SELECT * FROM table WHERE id = ?', [id]);
      if (result.length > 1) {
        throw new Meteor.Error('sql-delete', 'This is the primary company for others!');
      } else {
        liveDb.db.query('DELETE FROM table WHERE id = ?', [id]);
      }
    } catch(error) {
      if (_.has(error, 'reason')) {
        throw new Meteor.Error('sql-delete', error.reason);
      } else {
        console.log('sql-error', error);
        throw new Meteor.Error('sql-delete', 'There wan an sql error!');
      }
    }
  }
});

In the Meteor.wrapAsync(liveDb.db.query, liveDb.db); I had to pass both values or else I was getting this error TypeError: Cannot read property 'typeCast' of undefined.