Skip to main content

该项目可帮助您在 with 语句期间收集引发的错误。

项目描述

错误收集器

测试 测试覆盖率 可维护性 代码气候技术债务 更新 PyPI - Python 版本 推特网址

在 with 语句期间收集引发的错误。

特征

在某些情况下,我们不想立即引发错误。例如,在验证整个 HTTP POST 数据后向客户端返回错误 HTTP 响应的情况。

这个包有助于收集错误。

安装

pip install errorcollector

用法

多重错误收集器

比方说,有些数据模型具有单一属性。在处理这个数据模型之前,我们要验证属性。

前任:

from yourproduct.exceptions import ConvertError


class PostDataModel:
    def __init__(self, property_a_string: str, property_b_string: str):
        self._property_a_string = property_a_string
        self._property_b_string = property_b_string
        self.list_error = None

    def validate(self) -> bool:
        self.stock_convert_error(
            lambda: self.property_a_int,
            f"Property string A couldn't be converted to integer. Property string = {self._property_a_string}"
        )
        self.stock_convert_error(
            lambda: self.property_b_int,
            f"Property string B couldn't be converted to integer. Property string = {self._property_b_string}"
        )
        return bool(self.list_error)

    def stock_convert_error(self, method: Callable[[], Any], message: str) -> None:
        with MultipleErrorCollector(ConvertError, message, self.list_error):
            return method()

    @property
    def property_a_int() -> int:
        """May raise ValueError"""
        return int(self._property_a_string)

    @property
    def property_b_int() -> int:
        """May raise ValueError"""
        return int(self._property_b_string)

当我们调用 method时validate(),即使ValueError发生,也不会引发异常并且不会停止执行。

method()in 方法stock_convert_error()raisesValueError时, ConvertError设置raise ValueErrorinto__cause__设置为 property self.list_error

我们可以在验证后检查错误的详细信息。

单错误收集器

这是错误收集器的单一版本。这在需要通过多态性在集成方法中处理多个案例和单个案例的情况下可能很有用。

前任:

from yourproduct.exceptions import ConvertError


class PostDataModel:
    def __init__(self, property_string: str):
        self._property_string = property_string
        self.convert_error = None

    def validate(self) -> bool:
        self.stock_convert_error(
            lambda: self.property_int,
            f"Property string couldn't be converted to integer. Property string = {self._property_string}"
        )
        return self.convert_error is not None

    def stock_convert_error(self, method: Callable[[], Any], message: str) -> None:
        error_collector = SingleErrorCollector(ConvertError, message)
        with error_collector:
            method()
        self.convert_error = error_collector.error

    @property
    def property_int() -> int:
        """May raise ValueError"""
        return int(self._property_string)

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

errorcollector-1.0.0.tar.gz (6.1 kB 查看哈希)

已上传 source

内置分布

errorcollector-1.0.0-py3-none-any.whl (6.6 kB 查看哈希

已上传 py3