简体   繁体   中英

How to throw an error from server side and catch it from client side?

I am throwing an error from a server method using throw new Meteor.Error .

The client does not seem to pick it up and the callback's error argument is always undefined , but in the terminal it throws the error and restarts Meteor.

W20170413-17:27:28.900(1)? (STDERR) /home/xeconcepts/.meteor/packages/meteor-tool/.1.4.2-1-beta.1.si3hb0++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:280
W20170413-17:27:28.900(1)? (STDERR)                         throw(ex);
W20170413-17:27:28.900(1)? (STDERR)                         ^
W20170413-17:27:29.175(1)? (STDERR) Error: carte existe [204]
W20170413-17:27:29.175(1)? (STDERR)     at imports/api/users/methods.js:211:47

and the stripe methods or

const Stripe = require('stripe');
const stripe = Stripe("sk_test_pO*******MUDXjlF8v");

won't work only with

if(Meteor.isServer)

How to throw an error from server side and catch it from client side?

Method code:

export const addCCStudent = new ValidatedMethod({
    name: 'addCCStudent',
    validate: new SimpleSchema({
        id: {
            type: String
        },
        number: {
            type: String
        },
        dateMM: {
            type: String
        },
        dateYYYY: {
            type: String
        },
        cvc: {
            type: String
        }
    }).validator(),
    run(p) {
        try {
            if (Meteor.isServer) {
                const Fiber = require('fibers');
                const Stripe = require('stripe');
                const stripe = Stripe("*************");


                stripe.tokens.create({
                    card: {
                        "number": p.number,
                        "exp_month": p.dateMM,
                        "exp_year": p.dateYYYY,
                        "cvc": p.cvc
                    }
                }, function(err, token) {
                    console.log("tokenserr", err);
                    console.log("token", token);
                    if (!err) {
                        Fiber(function() {
                            //  console.log("p", p)
                            var user = Meteor.users.findOne({
                                _id: p.id
                            });
                            //console.log("addCCStudentuser", user);
                            if (user) {
                                var cCArray = user.profile.UserCards;
                                if (cCArray) {
                                    var exist = false;
                                    for (var i = 0; i < cCArray.length; i++) {
                                        if ((cCArray[i].number == p.number) && (cCArray[i].dateMM == p.dateMM) && (cCArray[i].dateYYYY == p.dateYYYY)) {
                                            exist = true
                                        }
                                    }

                                    if (exist) {
                                        throw new Meteor.Error(204, "carte existe");
                                    } else {

                                         Meteor.users.update({
                                            _id: p.id,
                                        }, {
                                            $push: {
                                                'profile.UserCards': { number: p.number, dateMM: p.dateMM, dateYYYY: p.dateYYYY }
                                            }
                                        });
                                    }
                                }
                            }
                        }).run();
                    } else {
                        // console.log("errerrerrerr", err.raw.message);
                        throw new Meteor.Error(204, err.raw.message);
                    }

                });
            }

        } catch (error) {
            console.log("error", error)
            throw new Meteor.Error(203, error.reason);
        }

    },
});

Ideally Meteor should catch any errors thrown directly within the method, but in your case this could be compounded by the fact that most of your errors are wrapped within a Fiber function call.

So it may be happening that you are throwing the error on server side, but it never bubbles up to the caller of the method (which is on client side, and which expects a response from the ValidatedMethod ).

Try returning the outcome of the Fiber function. Looking at the examples in the docs for fibers package, the try-catch block needs to be around the Fibers function call, not around the entire contents of the ValidatedMethod.

Additionally, you could also try adding return before all error statements. eg

return throw new Meteor.Error(204, "carte existe")

Note: It would also be good if you shared the client side code where you are trying to access this error.

Please try this. Inside the fiber where you throw an error, replace that by a function that throws the error

    if (exist) {
       ErrorFunction()
   }

Outside the fiber put the function

ErrorFunction() {
       throw new Meteor.Error(204, "carte existe");
}

See if the client is able to catch the same now.

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