
Stripe error handling
Stripe API libraries raise exceptions for many reasons, such as a failed charge, invalid parameters, authentication errors, and network unavailability. The Stripe recommends for writing code that gracefully handles all possible API exceptions.
Below Error Handling code is compatible with latest stripe API version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php ... try { // Use Stripe's library to make requests... } catch(\Stripe\Error\Card $e) { // Since it's a decline, \Stripe\Error\Card will be caught $body = $e->getJsonBody(); $err = $body['error']; print('Status is:' . $e->getHttpStatus() . "\n"); print('Type is:' . $err['type'] . "\n"); print('Code is:' . $err['code'] . "\n"); // param is '' in this case print('Param is:' . $err['param'] . "\n"); print('Message is:' . $err['message'] . "\n"); } catch (\Stripe\Error\RateLimit $e) { // Too many requests made to the API too quickly } catch (\Stripe\Error\InvalidRequest $e) { // Invalid parameters were supplied to Stripe's API } catch (\Stripe\Error\Authentication $e) { // Authentication with Stripe's API failed // (maybe you changed API keys recently) } catch (\Stripe\Error\ApiConnection $e) { // Network communication with Stripe failed } catch (\Stripe\Error\Base $e) { // Display a very generic error to the user, and maybe send // yourself an email } catch (Exception $e) { // Something else happened, completely unrelated to Stripe } ... ?> |
For old stripe versions i.e Stripe API v1.18.0 use below Error Handling code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php ... try { // Use Stripe's library to make requests... } catch(Stripe_CardError $e) { // Since it's a decline, \Stripe\Error\Card will be caught print('Message is:' . $e->getMessage() . "\n"); } catch (Stripe_InvalidRequestError $e) { // Invalid parameters were supplied to Stripe's API } catch (Stripe_AuthenticationError $e) { // Authentication with Stripe's API failed // (maybe you changed API keys recently) } catch (Stripe_ApiConnectionError $e) { // Network communication with Stripe failed } catch (Stripe_Error $e) { // Display a very generic error to the user, and maybe send // yourself an email } catch (Exception $e) { // Something else happened, completely unrelated to Stripe } ... ?> |
For more details please check .
Leave a Reply