簡體   English   中英

如何在Python中重用多個函數的異常處理代碼?

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

如何在Python中重用多個函數的異常處理代碼?

我正在開發一個將使用Stripe Python庫的項目。 https://stripe.com/docs/api/python#errors

這是他們的文檔中的一些示例代碼。

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

我需要編寫幾個函數來對Stripe系統執行各種調用來處理我的事務。 例如; 檢索令牌,創建客戶,為卡充電等等。我是否必須在每個函數中重復try / except代碼,或者有沒有辦法使try塊的內容動態化?

我想在我的Flask視圖代碼中使用這些各種函數作為條件,所以如果我能從每個函數中找回錯誤/成功消息,那也會有所幫助。

編寫一個裝飾器來調用try塊中的裝飾視圖,並處理任何與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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM