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.
        


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


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


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


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


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


@app.errorhandler(stripe.error.StripeError)
def stripe_generic_error(e):
    app.logger.error('Stripe.error.InvalidRequestError: %s', (e))
    record_payment_error('general-stripe-error')
    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