Python—将异常捕获作为泛型函数处理的简单方法
假设我有以下代码,再加上10个Python—将异常捕获作为泛型函数处理的简单方法,python,exception,try-catch,Python,Exception,Try Catch,假设我有以下代码,再加上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 conne
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)
比方说,我想在多个函数中使用所有这些相同的函数,除了它们的确切用法。我能想到的唯一方法是:
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...
有更好的方法吗?
谢谢我使用修饰符将函数中可能出现的某些类型的已知异常包装到另一种异常类型中。我们的目标是为客户机代码提供一个单一的异常类型。 这可能有助于您优雅地为每个函数重新提出一个
RESTClientException
,如果这是您主要追求的。但是,它不会转换任何错误消息。(也许这对你来说更重要,因为原始信息不够清晰!)
下面是它的使用方法:
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
回溯(最近一次呼叫最后一次):
文件“C:/symlinks/…/utilities/decorators.py”,第69行,在
测试()
文件“C:/symlinks/…/utilities/decorators.py”,第32行,在wrapped_func中
提升异常到提升(msg)
__main\uuuu.RESTClientException:包装值错误:出现问题
为什么不简单地将try/except包装成一个它自己的好主意!虽然我会简化它一点,并将其用于我的特定异常,但装饰师是一个很好的方法!
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