如何使用条带处理异常

问题描述 投票:0回答:1

我正在尝试将Stripe与我的django项目集成,所以我尝试创建一个PaymentIntent,如果与Stripe的网络通信失败,我将尝试这样做:

try:
    intent = stripe.PaymentIntent.create(
        amount=100,
        currency='usd'
    )
    return JsonResponse({
         'clientSecret': intent['client_secret']
    })
except stripe.error.CardError as e:
    pass
except stripe.error.RateLimitError as e:
    pass
except stripe.error.InvalidRequestError as e:
    pass
except stripe.error.AuthenticationError as e:
    pass
except stripe.error.APIConnectionError as e:
    try:
        intent_cancel = stripe.PaymentIntent.cancel(
            intent['id']
        )
    except Exception as e:
        # (If an exception is raised this means that the PaymentIntent was not created, I am right ?)
        # I redirect the user to the payment page and inform him
        # that a network problem has occurred and ask him to repeat his request
        pass
except stripe.error.StripeError as e:
    pass
except Exception as e:
    pass

我的问题是:

  • 1我处理异常的方式正确吗?
  • 2我可以将此逻辑应用于其他异常吗?
  • 3他们在文档中说我们应该使用idempotency_key重试失败的请求,如何实现呢?如果我重试失败的请求又再次失败,该怎么办?
django exception stripe-payments
1个回答
0
投票
您在同一try块中有2个Stripe API请求。这意味着,如果一个成功但另一个由于连接错误而失败,则您将两者都视为失败。更好的流程是每个try / catch块仅具有一个API操作。

您还要求在代码返回JSON对象后取消硬编码的PaymentIntent。由于返回不是有条件的,因此可能是无效代码。

这里出现连接错误时的取消逻辑在这里没有意义。如果连接失败且未创建意图,则应该只单击此路径,因此尝试取消不存在的PaymentIntent可能会导致另一个错误。相反,您应该在此处介绍重试逻辑。幸运的是,stripe-python专门针对网络错误内置了此功能:https://github.com/stripe/stripe-python#configuring-automatic-retries

一旦所有重试均失败,您可能应该将该日志记录在某处并通知您的用户发生了问题,以后应再试一次。

关于幂等性密钥,Stripe文档在此处有一个入门知识:https://stripe.com/docs/api/idempotent_requests?lang=python

© www.soinside.com 2019 - 2024. All rights reserved.