Throwing Meteor.Error does not reach the client

馋奶兔 提交于 2020-01-17 06:02:30

问题


So basically, the client calls the server using a Meteor.call. The server method then does some validations and calls a web service using a meteor package. If validation fails and a meteor error is thrown, it reaches the server. If the package response has an error, it only logs on the server. I need the error to reach the client.

Here's how the code looks like.

Client

Meteor.call('callService', (err, result) => {
    if(err) {
       console.log(err.reason);
    }
});

Server

Meteor.methods({
    'callService'(){
        if (!Meteor.user()) {
            // Error 1
            throw new Meteor.Error('insufficient-permissions', 'You need to login first');
        }
        // Using an meteor package to actually call the service
        package.callService(apiKey, (err, response) => {
            if (response.status === 'error') {
                 // Error 2
                  throw new Meteor.Error('service-error', response.message);
            }
        });
     },
});

In the server method, if an error is thrown at Error 1, it does reach the client, but Error 2 does not. Error 2 only logs on the server.


回答1:


I guess your package.callService() is async (given that it accepts a callback).

In that case, your Meteor method starts the async task, then continues its process and returns (since there is no more instructions), while the async task is still running (actually waiting for a response from your remote web service). Therefore your client Meteor call's callback receives a "no error" response.

Once your "Error 2" happens, the Meteor call is already completed, and the error can only be logged on the server.

If you want to "hang up" your method so that it waits for the result of your package.callService() to determine whether it is a success or an error and complete the Meteor call accordingly, you could try using Meteor.wrapAsync().

By the way, if you do use synchronous task to actually wait for a remote service, you would be interested in this.unblock() to allow your server to process other tasks (methods) instead of just idling.



来源:https://stackoverflow.com/questions/38690574/throwing-meteor-error-does-not-reach-the-client

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!