2015-03-10 9 views
6

Come posso riutilizzare il codice di gestione delle eccezioni per più funzioni in Python?Come posso riutilizzare il codice di gestione delle eccezioni per più funzioni in Python?

Sto lavorando a un progetto che utilizzerà la libreria Stripe Python. https://stripe.com/docs/api/python#errors

Questo è un codice di esempio dai loro documenti.

try: 
    # Use Stripe's bindings... 
    pass 
except stripe.error.CardError, e: 
    # Since it's 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's API 
    pass 
except stripe.error.AuthenticationError, e: 
    # Authentication with Stripe's 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 

Ho bisogno di scrivere diverse funzioni che svolgono diverse chiamate nel sistema Stripe al trattamento dei miei transazioni. Per esempio; recuperare un token, creare un cliente, caricare una carta, ecc. Devo ripetere il codice try/except in ogni funzione, oppure esiste un modo per rendere dinamico il contenuto del blocco try?

Mi piacerebbe utilizzare queste varie funzioni nel mio codice di visualizzazione Flask come condizionale, quindi se potessi ottenere un messaggio di errore/successo da ognuna di esse, sarebbe utile anche.

+0

Avete considerato un decoratore? – jonrsharpe

+0

Un gestore di contesto può essere utilizzato anche qui, se non si desidera che la gestione delle eccezioni si applichi a un'intera funzione. – dano

risposta

7

Scrivere un decoratore che chiama la vista decorata all'interno del blocco try e gestisce eventuali eccezioni relative a Stripe.

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