Meteor: Customizing errors messages from allow and

2019-07-03 22:07发布

I'm looking to standardize the error messages from allow and deny rules in Meteor. Rather than defining the errors in the callback on the client I'd like the server to respond with the correct error message so that I only have to define them once. From the docs on allow/deny:

The functions should return true if they think the operation should be allowed. Otherwise they should return false, or nothing at all (undefined).

However, if I throw an error in a deny function that Error gets sent down to the user. I.e. in a deny:

throw new Meteor.Error(404, "Not the owner");

and on the client:

SomeCollection.remove(someId, function(err, result) {
  console.log(err.message); // Outputs "Not the owner"
});

Seems like a simple way to display the same errors all over the site. Is this a valid way to go, even though the documentation clearly states that we should return true/false in a deny/allow?

标签: meteor
2条回答
甜甜的少女心
2楼-- · 2019-07-03 22:53

From this portion of the docs:

http://docs.meteor.com/#meteor_error

First three sentences:

If you want to return an error from a method, throw an exception. Methods can throw any kind of exception. But Meteor.Error is the only kind of error that a server will send to the client. 

It sounds to me like you're doing it right. I have to wonder though, shouldn't your UI never allow the user to have such a message come up? Other than "Oops, you shouldn't have been allowed to do that. Reverting your action." in case of a bug that accidentally allows an unauthorized query to go through.

查看更多
【Aperson】
3楼-- · 2019-07-03 22:55

You cannot throw an exception in Meteor allow / deny callbacks. Doing so will break the chain of callbacks that Meteor will check through to ensure a document's operation go through.

Example:

Meteor will check through AT LEAST ONE allow rules, as long as 1 returns true, the operation succeeds.

Allow 1 -> Allow 2 -> Allow 3

Meteor will also check through ALL the deny rules, as long as 1 returns true, the operation fails

Deny 1

If an exception is thrown on Allow 1 instead of return false (as it should if the user is not allowed to do something), Meteor never checks Allow 2 and 3 even if they would return true. So that breaks the chain.

查看更多
登录 后发表回答