python 通过装饰器 实现try except 异常捕捉

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __DATE__:2023/5/12
from loguru import logger
from functools import wraps
import traceback

logger.add(
    '../log/{time:YYYY-MM-DD}.log',  # 日志文件路径及日志文件名格式:2023-01-30.log
    rotation='00:00',  # 每天00:00 自动生成新的日志文件
    retention='30 day', mode='a+',  # 保留多久的日志文件
    backtrace=True, diagnose=True,  # 记录完整的错误信息
    encoding='utf-8',  # 日志文件编码
    enqueue=True,
)


# 定义装饰器error_handler
def error_handler(func):
    @wraps(func)  # 关键行, 旨在消除装饰器对原函数造成的影响,即对原函数的相关属性进行拷贝,已达到装饰器不修改原函数的目的。
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            msg = traceback.format_exc()
            logger.error(msg)
            return f'error: {msg}'

    return wrapper  # 返回函数名


@error_handler
def fun_1():
    a = 1 / 0
    return a


if __name__ == '__main__':
    res = fun_1()
    print("返回结果:", res)
D:\Anaconda3\envs\fastapi\python.exe F:/WorkCode/AlgorithmServer/utils/error_log.py
返回结果: error: Traceback (most recent call last):
  File "F:/WorkCode/AlgorithmServer/utils/error_log.py", line 23, in wrapper
    return func(*args, **kwargs)
  File "F:/WorkCode/AlgorithmServer/utils/error_log.py", line 32, in fun_1
    a = 1/0
ZeroDivisionError: division by zero

2023-05-12 16:05:28.480 | ERROR    | __main__:wrapper:26 - Traceback (most recent call last):
  File "F:/WorkCode/AlgorithmServer/utils/error_log.py", line 23, in wrapper
    return func(*args, **kwargs)
  File "F:/WorkCode/AlgorithmServer/utils/error_log.py", line 32, in fun_1
    a = 1/0
ZeroDivisionError: division by zero


Process finished with exit code 0

参考自:用Python装饰器给函数自动加上try except

解决多次写try  except  的繁琐,直接import 装饰器即可

你可能感兴趣的:(python,开发语言)