Error handling in meteor

Hello all,

I’m a bit new to meteor, and I have one somewhat simple question to ask. I am following the tutorial provided on the official site here: https://www.meteor.com/tutorials/blaze/creating-an-app. And I noticed that during the “security with methods” step, if you don’t create the Meteor.methods in the correct place or create them at all, no errors will be thrown when trying to run the application. Is there a way or some form of library I can use to make sure that the function exists before I call it?

If this question has been answered before or is in the wrong place, please let me know!

Thanks in advance!

1 Like

Write a test. With sanjo:jasmine in server integration mode:

describe('myMethod', function () {
  it('is defined', function () {
    expect(function () {
      Meteor.call('myMethod');
    }).not.toThrow();
  })
})

The would be the starting point. When you write more tests for the method, this test becomes obsolete.

1 Like

I’m not entirely sure what you mean… Do you want to manage an error on the client with a meteor call? You can use the async callback. Take for example the short method below

Meteor.methods({
  'addToGroup': function (userId, group) {
    if (Roles.userIsInRole(this.userId, 'can-add', group)) {
      Roles.addUsersToRoles(userId, 'can-view', group);
      return Meteor.users.findOne(userId);
    } else {
      throw new Meteor.Error(401, "Must be admin of group to add users");
    }
  }
});

Then client side:

Template['profile'].events({
  'click button[data-action="add-to-group"]': function (e, template) {
    var userId = Router.current().params._id;
    var group = $(e.target).data('groupId');
    Meteor.call('addToGroup', userId, group, function (error, user) {
      if (error) {
        // do something with it
        alert(error.message);
      }
    });
  }
});
2 Likes

Welcome to javascript?

Other than what Sanjo recommends (I’m going down this path to reduce regression issues as my app matures) there’s nothing that can make sure every reference to a method/hook/helper/template/var/session key/etc… is correct.

Even if you had the method but spelt it incorrectly or with different casing or change the call/method at a later date, your code will break.

Angular explicitly does not throw an error if you refer to a scoped variable that doesn’t exist because the scope is dynamic and it assumes that you meant to write it like that.
So this is not a meteor specific problem. And you’ll have to be very careful with refering to things and refactoring your code. sigh I miss Resharper…