gpt4 book ai didi

Python - 将异常捕获视为通用函数的简单方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:06 25 4
gpt4 key购买 nike

假设我有以下代码,再加上 10 个代码。

try:
session.get('http://www.google.com')
except rex.MissingSchema as e:
raise RESTClientException('Bad URL for request: ' + str(url), 'error:url', e)
except rex.ConnectionError as e:
raise RESTClientException('Cannot connect for token', 'error:connection', e)
except rfcex.InsecureTransportError as e:
raise RESTClientException('Verify certificates True without https', 'error:https', e)

假设我想在多个函数中使用所有这些相同的 except,它们到底是怎样的。我能想到的唯一方法是:

try:
session.get('http://www.google.com')
except Exception as e:
interpret_exception(e)

def interpret_exception(e)
if isinstance(e, rex.MissingSchema):
raise RESTClientException('Bad URL for request: ' + str(url), 'error:url', e)
elif isinstance(e, rex.ConnectionError):
raise RESTClientException('Cannot connect for token', 'error:connection', e)
#etc...

有更好的方法吗?谢谢

最佳答案

我使用装饰器的目的是将函数中可能发生的某些类型的已知异常包装到另一种异常类型中。目标是为客户端代码提供单一异常类型来异常(exception)。这可能会帮助您优雅地为每个函数重新引发 RESTClientException(如果这是您主要追求的目标)。但是它不会转换任何错误消息。 (也许这对你来说更重要,因为原始消息不够清晰!?)

def wrap_known_exceptions(exceptions_to_wrap, exception_to_raise):
"""Wrap a tuple of known exceptions into another exception to offer client
code a single error to try/except against.

Args:
exceptions_to_wrap (instance or tuple): Tuple of exception types that
are caught when arising and wrapped.
exception_to_raise (Exception type): Exception that will be raised on
an occurence of an exception from ``exceptions_to_wrap``.

Raises:
exception_to_raise's type.
"""
def closure(func):

@wraps(func)
def wrapped_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except exceptions_to_wrap as exception_instance:
msg = u"wraps {0}: {1}"
msg = msg.format(type(exception_instance).__name__, exception_instance)
raise exception_to_raise(msg)

return wrapped_func
return closure

使用方法如下:

class RESTClientException(Exception):
"""RESTClientException"""

@wrap_known_exceptions(ValueError, RESTClientException) # could also be a tuple
def test():
raise ValueError("Problem occured")

test()

输出:

Traceback (most recent call last):
File "C:/symlinks/..../utilities/decorators.py", line 69, in <module>
test()
File "C:/symlinks/..../utilities/decorators.py", line 32, in wrapped_func
raise exception_to_raise(msg)
__main__.RESTClientException: wraps ValueError: Problem occured

关于Python - 将异常捕获视为通用函数的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com