How can I reuse exception handling code for multiple functions in Python?
I am working on a project that will use the Stripe Python library. https://stripe.com/docs/api/python#errors
This is an example code from their docs.
try: # Use Stripe bindings... pass except stripe.error.CardError, e: # Since it a decline, stripe.error.CardError will be caught body = e.json_body err = body['error'] print "Status is: %s" % e.http_status print "Type is: %s" % err['type'] print "Code is: %s" % err['code'] # param is '' in this case print "Param is: %s" % err['param'] print "Message is: %s" % err['message'] except stripe.error.InvalidRequestError, e: # Invalid parameters were supplied to Stripe API pass except stripe.error.AuthenticationError, e: # Authentication with Stripe API failed # (maybe you changed API keys recently) pass except stripe.error.APIConnectionError, e: # Network communication with Stripe failed pass except stripe.error.StripeError, e: # Display a very generic error to the user, and maybe send # yourself an email pass except Exception, e: # Something else happened, completely unrelated to Stripe pass
I need to write some functions that make various calls on the Stripe system to process my transactions. For instance; get a token, create a client, charge a card, etc. Should I repeat the try / except code in each function or is there a way to make the contents of the test block dynamic?
I would like to use these various functions in my Flask view code as conditional, so if I could get an error / success message from each of them, that would be useful too.
Corey source share