triniwiz / nativescript-plugins

Apache License 2.0
78 stars 50 forks source link

[nativescript-stripe] Better error handling #167

Open sebj54 opened 1 year ago

sebj54 commented 1 year ago

Hi there!

I've been using this plugin for a while, but with a custom patch in order to have a better error handling.

I had an issue in the past on Android where a basic Exception was thrown instead of a StripeException. In this case, calling error.getLocalizedMessage() fails and another exception is thrown.

So I added a _getLocalizedError function, which will test if the error is an instance of StripeException and thus call getLocalizedMessage(). It will also add Stripe's error code and decline code to the error returned.

Here is the function for Android:

_getLocalizedError(error) {
    let localizedError
    if (error instanceof com.stripe.android.exception.StripeException) {
        localizedError = new Error(error.getLocalizedMessage() || error.getMessage());
        if (error.stripeError) {
            localizedError.code = error.stripeError.code;
            localizedError.declineCode = error.stripeError.declineCode;
        }
    } else {
        localizedError = new Error(error.message);
    }
    return localizedError
}

And the one for iOS:

_getLocalizedError(error, intent) {
    const localizedError = new Error(error.localizedDescription);
    if (intent?.lastPaymentError) {
        localizedError.code = intent.lastPaymentError.code;
        localizedError.declineCode = intent.lastPaymentError.declineCode;
    }
    return localizedError
}

Then I replaced all these calls by my function:

- cb(new Error(error.getMessage() || error.getLocalizedMessage()), null);
+ cb(this._getLocalizedError(error), null);

I was wondering if you were interested to add this to the plugin. I would be glad to make a PR in that case :)