Tuesday 8 September 2020

How can I reuse exception handling code for multiple functions in Python?

 Write a decorator that calls the decorated view within the try block and handles any Stripe-related exceptions.

from functools import wraps

def handle_stripe(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except MyStripeException as e:
            return my_exception_response
        except OtherStripeException as e:
            return other_response

    return decorated

@app.route('/my_stripe_route')
@handle_stripe
def my_stripe_route():
    do_stripe_stuff()
    return my_response


from : https://stackoverflow.com/questions/28965795/how-can-i-reuse-exception-handling-code-for-multiple-functions-in-python

No comments:

Post a Comment