python - 在 Python 中引发错误的一种非常优雅的方式是什么

标签 python exception error-handling raise raiserror

我目前正在编写一个银行应用程序,下面您可以看到我的代码:

from customer import Customer
from exceptions import KeyError

class Bank(object):
    """ All the bank operations are contained in this class e.g customer Registration """

    def __init__(self, name):
        self.name = str(name)
        self.customers = dict()
        self.registration_customer(name)

    def registration_customer(self, name):
        """ Registration of a new user to the bank
        Args:
            name (str): name of the customer
        """
        name = str(name)
        if not self.customers.get(name, None):
            self.customers[name] = Customer(name)

    def close_customer_account(self, name, account_type):
        """ close an account of a customer by name and account_type
        Args:
            name (str) : name of the account holder
            account_type (str) : type of account
        """
        name = str(name)
        account_type = str(account_type)
        customer = self.customers.get(name, None)
        if customer:
            customer.close_account(account_type)

    def get_customer_info(self, name):
        """ get customer info
        Args:
            name (str) : name of the customer
        """

        if not self.customers[name]:
            raise KeyError('I am sorry! Customer does not exist')

        return self.customers[name]

引发错误

如果您看到 get_customer_info 函数,并且 name 不存在,那么我将引发错误。假设银行应用程序非常关键,这是我在 Python 中引发错误的最佳方法吗?您还可以假设这是生产级别的代码。

 def get_customer_info(self, name):
        """ get customer info
        Args:
            name (str) : name of the customer
        """

        if not self.customers[name]:
            raise KeyError('I am sorry! Customer does not exist')

        return self.customers[name]

最佳答案

我认为这取决于软件的需求。 理想情况下,应在提交表单之前告知用户其输入无效,使提交按钮变灰并提示输入用户名。

如果提交,应记录该错误,以便生成统计数据,如果这是一个非常严重或不寻常的错误,则应自动生成电子邮件并发送给相关人员。

用户应该被重定向回输入表单并且他们之前提交的信息仍然完好无损,不要强制用户重新提交整个表单。

关于python - 在 Python 中引发错误的一种非常优雅的方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712812/

相关文章:

sql - 开始尝试在SQL Server 2005上捕获,如何将ERROR_stuff发送给调用的父级?

java - 抓取或知道 jar 中发生错误?

python - Flask:如何检查一对多反向引用是否存在

c# - 用户代码未处理常规转换 InvalidOperationException

ios - -[MPMoviePlayerControllerNew _moviePlayerDidBecomeActiveNotification :] 中的断言失败

c# - 事件处理程序中抛出的 WPF 异常被吞噬了吗?

java - 处理Java中某些情况下不希望返回类型的函数返回

python - 将 pandas 列中的字典转换为数据框

python - F# 字典初始化就像在 Python 中一样

python - 将列表转换为字符串并允许使用分隔符