Skip to content

Error Handling

pakrym-stripe edited this page Mar 21, 2022 · 8 revisions

An error is only thrown when you don't pass a required argument to a resource method. All REST or otherwise asynchronous errors will be available as the first argument of any Stripe method's callback:

stripe.customers.create({...}, function(err, result) {});

Or in the form of a rejected promise:

stripe.customers.create({...}).then(
  function(result) {},
  function(err) {}
);

The error object you receive will have one of the following types:

switch (err.type) {
  case 'StripeCardError':
    // A declined card error
    err.message; // => e.g. "Your card's expiration year is invalid."
    break;
  case 'StripeInvalidRequestError':
    // Invalid parameters were supplied to Stripe's API
    break;
  case 'StripeAPIError':
    // An error occurred internally with Stripe's API
    break;
  case 'StripeConnectionError':
    // Some kind of error occurred during the HTTPS communication
    break;
  case 'StripeAuthenticationError':
    // You probably used an incorrect API key
    break;
  case 'StripeRateLimitError':
    // Too many requests hit the API too quickly
    break;
  case 'StripePermissionError':
    // Access to a resource is not allowed
    break;
  case 'StripeIdempotencyError':
    // An idempotency key was used improperly
    break;
  case 'StripeInvalidGrantError':
    // InvalidGrantError is raised when a specified code doesn't exist, is
    // expired, has been used, or doesn't belong to you; a refresh token doesn't
    // exist, or doesn't belong to you; or if an API key's mode (live or test)
    // doesn't match the mode of a code or refresh token.
    break;
}

Typescript

When using Typescript, errors can be handled by first checking against the Stripe.StripeError type:

import Stripe from "stripe";

stripe.customers.create({...}).then(
  function(result) {},
  function(err) {
    if (err instanceof Stripe.errors.StripeError) {
      // Break down err based on err.type
    } else {
      // ...
    }
  }
);

The error types are available in types/Errors.d.ts.