简体   繁体   English

如何在Python中重用多个函数的异常处理代码?

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

How can I reuse exception handling code for multiple functions in Python? 如何在Python中重用多个函数的异常处理代码?

I am working on a project that will use the Stripe Python library. 我正在开发一个将使用Stripe Python库的项目。 https://stripe.com/docs/api/python#errors https://stripe.com/docs/api/python#errors

This is some example code from their docs. 这是他们的文档中的一些示例代码。

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

I need to write several functions that perform various calls into the Stripe system to process my transactions. 我需要编写几个函数来对Stripe系统执行各种调用来处理我的事务。 For example; 例如; retrieve a token, create a customer, charge a card, etc. Do I have to repeat the try/except code in each function, or is there a way to make the contents of the try block dynamic? 检索令牌,创建客户,为卡充电等等。我是否必须在每个函数中重复try / except代码,或者有没有办法使try块的内容动态化?

I'd like to use these various functions in my Flask view code as conditionals so if I could get back an error/success message from each of them, that would be helpful too. 我想在我的Flask视图代码中使用这些各种函数作为条件,所以如果我能从每个函数中找回错误/成功消息,那也会有所帮助。

Write a decorator that calls the decorated view within the try block and handles any Stripe-related exceptions. 编写一个装饰器来调用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