上下文和装饰器优雅,灵活地处理异常
2019-03-19 本文已影响0人
hugoren
如何优雅地处理异常
- 尽量精确捕获异常
- 如果是接口或函数方式,尽量高度抽象,不要影响了代码的可读性和灵活性
上下文方式
# 上下文处理异常
class RaiseCode:
REQUEST_TIMEOUT = "请求超时"
zero_divisor = ZeroDivisionError({"retcode": 1, "stderr": "被除数不能为零"})
class RaiseContent:
def __init__(self, captures, code_name):
self.captures = captures
self.code = getattr(RaiseCode, code_name)
def __enter__(self):
self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type == self.captures:
raise self.code
def test_raise_1():
result = 1 / 0
return result
def test_raise_2():
with RaiseContent(ZeroDivisionError, "zero_divisor"):
result = 1 / 0
return result
def main():
try:
print(test_raise_2())
except Exception as e:
print(e)
if __name__ == "__main__":
main()
测试
image.png装饰器方式
from functools import wraps
def decorate_raise(func):
@wraps(func)
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return e
return wrap
@decorate_raise
def test_raise_3():
if 0 != 1:
raise Exception({"retcode": 1, "stderr": "为了测试特意抛出的异常"})
def main_decorate():
print(test_raise_3())