更改上下文管理器中的异常类型

问题描述 投票:0回答:1

我目前的代码看起来像这样分散在我的代码库中:

try: 
    something()
catch Exception as exc:
    raise SomethingError from exc

我想编写一个上下文管理器来删除一些样板:

with ExceptionWrapper(SomethingError):
    something()

看起来可以在上下文管理器中抑制异常 - 请参阅:

contextlib.suprress
https://docs.python.org/3/library/contextlib.html#contextlib.suppress)。看起来不可能更改引发的异常。

但是,我还没有找到关于上下文管理器的

__exit__
函数的返回值是什么的明确文档。

python exception
1个回答
0
投票

这种简单的上下文管理器最容易使用

contextlib.contextmanager
来实现,它从生成器中创建一个上下文管理器。只需用 try-except 逻辑包装第一个
yield
语句,并在 except 块中引发所需的异常:

import contextlib

@contextlib.contextmanager
def exception_wrapper():
    try: 
        yield
    except Exception as exc:
        raise SomethingError() from exc

可以像这样使用:

>>> with exception_wrapper():
...     raise Exception("ding!")

Traceback (most recent call last):
  File "<stdin>", line 4, in exception_wrapper
  File "<stdin>", line 2, in <module>
Exception: ding!

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
    self.gen.throw(typ, value, traceback)
  File "<stdin>", line 6, in exception_wrapper
__main__.SomethingError
© www.soinside.com 2019 - 2024. All rights reserved.