【发布时间】:2015-03-10 14:02:22
【问题描述】:
如何在 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 视图代码中使用这些不同的函数作为条件,所以如果我能从它们中的每一个返回错误/成功消息,那也会很有帮助。
【问题讨论】:
-
你考虑过装饰师吗?
-
如果您不希望异常处理应用于整个函数,也可以在此处使用上下文管理器。
标签: python function exception exception-handling flask