简体   繁体   中英

Throwing Meteor.Error does not reach the client

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM