cannot catch Meteor.Error in client when error thrown from server side of meteor method

223 Views Asked by At

I have a meteor call and meteor method. When I throw Meteor error then it is not caught inside meteor call's error but instead in response

Here is my meteor method

Meteor.call("updateFtIndex", id, $(`#idx-${id}`).val(), function (error, result) {
    if (error) {
        console.log('error: ', error.reason);
    }
    else {
        console.log('result', result);
    }
})

and here is my meteor method

Meteor.methods({
    updateFtIndex: function (_id, index) {
        try {
            let isIndexExists = Meteor.users.findOne({_id, "profile.featuredProviderIndex": index }, {fields: 
             {"profile.featuredProviderIndex": 1}});
            if(isIndexExists){
                console.log('isIndexExists: ', isIndexExists);
                throw new Meteor.Error( 400, "Sorted index already exist !!!");
            }
            else {
                console.log("else");
                return Meteor.users.update({_id}, { $set: { "profile.featuredProviderIndex": index } });
            }
        } catch (error) {
            return error
        }
    }
})

And I get the thrown error inside result of meteor call Can somebody tell me what is wrong with the code ?

2

There are 2 best solutions below

0
Abhishek Goswami On

You are returning error instead of throwing it from catch block.

1
Ricardo Aragão On

You are catching the throw and your catch is returning the error but the better way to return an error to the front is your change it to this:

    try {
        let isIndexExists = Meteor.users.findOne({_id, "profile.featuredProviderIndex": index }, {fields:  {"profile.featuredProviderIndex": 1}});
        if(isIndexExists){
            console.log('isIndexExists: ', isIndexExists);
            throw new Meteor.Error( 400, "Sorted index already exist !!!");
        }
        else {
            console.log("else");
            return Meteor.users.update({_id}, { $set: { "profile.featuredProviderIndex": index } });
        }

    } catch (e) {
        throw new Meteor.Error(400, e.toString());
    }