【问题标题】:Best way to use Python classes for creating Stripe objects and handling errors使用 Python 类创建 Stripe 对象和处理错误的最佳方式
【发布时间】:2021-06-29 09:19:21
【问题描述】:

我有一个与 Stripe 集成的 Django 应用程序。根据Stripe documentation,我遵循他们的建议,使用 try/except 子句来处理在创建客户、产品、价格等过程中可能出现的任何错误。

为了保持 DRY,我创建了一个 Python 基类,特定于对象的子类从该基类继承。这样我可以自定义每个子类的 create_method 来创建一个特定的对象,但仍然将所有错误处理保留在一个地方(父类)。这一切似乎都运行良好,但我想知道是否有人对此方法有任何反馈或建议改进?谢谢!

import stripe

from django.conf import settings

stripe.api_key = settings.STRIPE_SECRET_KEY

class StripeObject():
    """
    Base class for all Stripe objects (e.g., Customer, Product, Price)
    """

    create_method = None

    def __init__(self, common_kwargs={}, instance_kwargs={}):
        self.common_kwargs = common_kwargs
        self.instance_kwargs = instance_kwargs

    def handle_error(self, e):
        try:
            print('Code is: %s' % e.code)
            print('Message is: %s' % e.user_message)
        except KeyError:
            print('One of the following keys was not found in the error response:\ncode or user_message.')

    def create(self):
        try:
            return self.create_method(**self.common_kwargs, **self.instance_kwargs)
        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            self.handle_error(e)
        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            self.handle_error(e)
        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            self.handle_error(e)
        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            self.handle_error(e)
        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            self.handle_error(e)
        except Exception as e:
            # Something else happened, completely unrelated to Stripe
            self.handle_error(e)

class StripeCustomer(StripeObject):
    create_method = stripe.Customer.create

class StripeProduct(StripeObject):
    create_method = stripe.Product.create

class StripePrice(StripeObject):
    create_method = stripe.Price.create

    def __init__(self, instance_kwargs):
        common_kwargs = {
            "currency": "usd"
        }
        super().__init__(common_kwargs=common_kwargs, instance_kwargs=instance_kwargs)

这些类的结果接口是:

product = StripeProduct({"name":"Product Name"}).create()

【问题讨论】:

    标签: python django oop stripe-payments


    【解决方案1】:

    您只需要捕获 stripe.error.StripeError 这个 except 将捕获所有扩展 StripeError 的异常(如 AuthenticationErrorInvalidRequestErrorRateLimitError 等);

    其他异常与 Stripe 包无关,无需捕获。

    同样使用except Exception 可以捕获所有异常,但使用它不是一个好习惯,因为它的异常子句过于宽泛。

    【讨论】:

    • 我明白了。说得通。谢谢!
    猜你喜欢
    • 2013-01-20
    • 2021-05-20
    • 2014-09-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2021-01-31
    相关资源
    最近更新 更多