gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:46:39 26 4
gpt4 key购买 nike

如何在 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 系统执行各种调用以处理我的交易。例如;检索 token 、创建客户、为卡充值等。我是否必须在每个函数中重复 try/except 代码,或者是否有办法使 try block 的内容动态化?

我想在我的 Flask View 代码中使用这些不同的函数作为条件,所以如果我能从它们中的每一个返回错误/成功消息,那也会很有帮助。

最佳答案

编写一个装饰器,在 try block 中调用装饰 View 并处理任何与 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

关于python - 如何在 Python 中为多个函数重用异常处理代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28965795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com