user3413723
user3413723

Reputation: 12213

Equivalent of PHP Die(): how to stop function's execution on server

I am building a Meteor application with some custom authentication in addition to the built-in accounts MDG package. I want to have a function I call at the front of Meteor methods to verify authentication. If authentication fails, I would like to do the equivalent of PHP's die() function - return a message and stop execution.

I could always do something like this: if(!checkAuth()) return "Not Authenticated", however it would be nice if I could just do checkAuth() and that function takes care of stopping execution if correct permissions are not met.

Is there a way to do this?

Upvotes: 1

Views: 103

Answers (1)

Kyll
Kyll

Reputation: 7139

The easy way is to throw a new Meteor.Error. If not caught it will stop the currently running function, and if it is thrown from a method or a subscription it will appear on the client-side.

function checkAuth(user) {
  if(!isAuthenticated(user)) {
    throw new Meteor.Error('not-authenticated', 'Users need to be authenticated to do foo')
  }
}

The above thrown error server-side will appear on the client with the reason and the details. It allows you to do custom error handling tailored to whatever is happening. If any other kind of error is thrown, it will appear as "500 Internal server error".

Note that this mechanism is similar to check. You could even use a custom Match pattern :

check(user, MyPatterns.authenticatedUser)

Upvotes: 3

Related Questions