【问题标题】:Get error when using custom exception in python在 python 中使用自定义异常时出错
【发布时间】:2021-03-06 23:48:56
【问题描述】:

我有插入数据的自定义例外:

class ErrorOnInsert(BaseException):
    """Exception raised for errors in insert data to db

    Attributes:
        resource -- resource name
        message -- explanation of the error
    """

    def __init__(self, resource: str):
        self.message = 'Failed to insert data for {}!'.format(resource)
        super().__init__(self.message)

这个插入函数中使用了异常到mongo:

def _add(self, data: RunnerRating):
        try:
            dict_data = data.as_dict()

            self.collection[self.document_name].insert_one(
                        dict_data)
            self.list_data.add(data)
        except ErrorOnInsert(self.document_name) as e:
            raise e

我尝试使用self.repo._add(None) 测试异常,但它显示如下错误:

失败的测试/集成/test_repo.py::RatingRepoTest::test_add - TypeError:捕获不从 BaseException 继承的类是 不允许

【问题讨论】:

    标签: python mongodb


    【解决方案1】:

    您的语法看起来像是一个模式匹配的陷阱(这在 Python 中不是这样)。

    你在找吗

    def _add(self, data: RunnerRating):
        try:
            dict_data = data.as_dict()
            self.collection[self.document_name].insert_one(dict_data)
            self.list_data.add(data)
        except Exception as e:
            raise ErrorOnInsert(self.document_name) from e
    

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 2011-01-16
      • 2019-06-02
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      相关资源
      最近更新 更多