Handling rejection of subscriptions: return nothing or emit error?

I’ve found two ways through my experiments to “reject” certain subscriptions.

Meteor.publish('SecretUserData', function (userId) {
  if (this.userId && Roles.userIsInRole(this.userId, 'admin')) {
    // admin can see everything.
    return Meteor.users.find();
  } else if (this.userId) {
    // other users can see profile.
    return Meteor.users.find({}, {
      fields: {
        profile: 1;
      }
    });
  } else {
    // otherwise, they are rejected.
    this.error(new Meteor.Error(401, "You can't get that data!"));
    this.ready();
  }
});

// ... on the client
Meteor.subscribe('SecretUserData', template.data.user._id, {
  onError: function () {
    if (error.message === 401) {
      Router.go('login');
    }
  }
})

Or is it better to just return nothing on the client and handle the error there? That is

// client
Meteor.subscribe('SecretUserData', template.data.user._id);
var user = Meteor.users.findOne();
if (!user && !Meteor.userId()) {
  Router.go('login');
}
3 Likes

I would personally go with the top option. It seems like you could probably write a plugin to handle the onError stuff easier in Iron Router and cut down on that code.

Also, for the love of god, please stop passing in a userId to your publication. I can see from your code you don’t even use it, so you don’t have a security hole at least, but be more mindful of what you pass to your publications :wink:

4 Likes