utils.context_managers module

context_managers.py

  • 上下文管理器

  • 错误管理器

@Author pht @Date 2022-07-04

class utils.context_managers.Checker(untrapped: Type[BaseException] | Tuple[Type[BaseException]] = (), output: str = '发生了意料之外的错误,请检查输入')[源代码]

基类:object

错误管理器

记录当前状态发生错误应当给出的提示信息,发生错误时抛出AssertionError

示例代码

``` try:

with Checker(AssertionError) as checker:

checker.assert_(1 == 1, '相等比较异常') value, div = 10, 0 checker.assert_(value > 0, '被除数应为正数', '除数为0') value /= div checker.set_output(f'不存在活跃度为{value}的同学') student = Person.objects.get(point=value)

except AssertionError as e:

content = wrong(str(e))

```

assert_(expr, output: str = None, next: str = None)[源代码]

断言,可设置本步和下一步的错误提示,用于无异常的简单表达式

参数:
  • expr -- 支持__bool__的表达式值

  • output (str, optional) -- 本步的错误提示, defaults to None

  • next (str, optional) -- 本步成功后接下来的错误提示, defaults to None

set_output(output: str)[源代码]

设置错误提示,当发生错误时,抛出对应提示的AssertionError

参数:

output (str) -- 错误提示

set_untrapped(exceptions: Type[BaseException] | Tuple[Type[BaseException]] = ())[源代码]

设置不捕获的异常类型

参数:

exceptions (Union[Type[Exception], Tuple[Type[Exception]]], optional) -- 直接抛出的异常类别,暂不支持子类, defaults to ()