Handle stripe errors and exceptions in Flask

Exception handling for APIs from external vendors is crucial in your Flask application. It is especially true when the API deals with payments, such as Stripe

Stripe has already made life simpler by providing a strong suit of exceptions. So, all we have to do is associate appropriate "error handlers" for each of the exceptions.

Setting up try-catch blocks for each error, as their minimal example suggests, is probably not a great strategy.

If you are using Stripe, you must be using it at many places within your application. Try-catch blocks with every function-call will lead to a lot of redundant code.

We will keep our error handling strategy simple. We will perform the following steps in the case of an error.

  • Catch the error
  • Record the error with all its meta-data in an events table
  • Log the error along with its stack-trace our logger and mail the admin
  • Present a beautiful page to the user apologizing for any problems on our end and requesting them to verify their details, if the problem lies on their side.

def stripe_card_error(e):
    app.logger.error('Stripe.error.CardError: %s', (e))
    return render_template('errors/card-declined.jinja2'), 200

def stripe_ratelimit_error(e):
    app.logger.error('Stripe.error.RateLimitError: %s', (e))
    return render_template('errors/stripe-error.jinja2'), 200

def stripe_invalid_request_error(e):
    app.logger.error('Stripe.error.InvalidRequestError: %s', (e))
    return render_template('errors/stripe-error.jinja2'), 200

def stripe_authentication_error(e):
    app.logger.error('Stripe.error.AuthenticationError: %s', (e))
    return render_template('errors/stripe-error.jinja2'), 200

def stripe_api_connection_error(e):
    app.logger.error('Stripe.error.APIConnectionError: %s', (e))
    return render_template('errors/stripe-error.jinja2'), 200

def stripe_generic_error(e):
    app.logger.error('Stripe.error.InvalidRequestError: %s', (e))
    return render_template('errors/stripe-error.jinja2'), 200


If you need help logging errors or warnings, check out setting up an application log for Flask for recording and emailing errors