如何优雅地处理异常
- 尽量精确捕获异常
- 如果是接口或函数方式,尽量高度抽象,不要影响了代码的可读性和灵活性
上下文方式
# 上下文处理异常
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())
测试
image.png
参考:
https://github.com/piglei/one-python-craftsman/blob/master/zh_CN/6-three-rituals-of-exceptions-handling.md
网友评论