异常

from abc import *

# 思路:遇到异常后、从异常字典匹配异常,匹配到了:调用匹配到的异常处理函数进行结果处理
# 没匹配到,注册一个异常子类

# key: 异常类型   value:msg
exist_exception_dict = {'Nobody': 'BodyNoneFunc','BodyNotJson':"BodyNotJsonFunc"}

# 自定义异常类
class MyException(Exception): def __init__(self, msg=''): self.msg = msg def BodyNoneFunc(self): print('没有body体应该做哪些操作。。。') def BodyNotJsonFunc(self): print('body不是json格式应该做哪些操作。。。') def UserDefineException(name, msg=''): if name in exist_exception_dict: print('有该异常类 执行异常') getattr(MyException(),exist_exception_dict[name])() else: # 没有该异常 # 1.添加到异常字典 exist_exception_dict[name] = msg class_dict = {'msg': msg} # 2. 创建异常子类,并继承MyException setattr(MyException, name, '') type(name, (MyException,), class_dict) print('MyException所有子类', MyException.__subclasses__())
import json

def JsonDecodeErrorFun():
    print('必须是json格式 JsonDecodeErrorFunc')

exceptionPool = {
    json.JSONDecodeError:JsonDecodeErrorFun,

}

def Do(fn,*params):
    try:
        fn(*params)
        print('0没异常')
        return True

    except Exception as e:
        print('有异常',e)
        if e in exceptionPool:
            print('在异常池')
            return exceptionPool[e]()
        print('不在异常池')
        return False



Do(json.loads,111)
# 使用
from kunpengException import UserDefineException,exist_exception_dict, MyException
import json




body = 123
try:
    UserDefineException('BodyNotJson1', 'body体必须是json')  # para: 异常类名,msg
    print(2222,MyException.__subclasses__())
    json.loads(body)
    print('BodyNotJson' in 1)
    print(111111,type(MyException.__dict__))

    raise kunpengException.BodyNotJson1


except kunpengException.BodyNotJson1 as e:
    print(e)

print('
 except_dict 字典:', exist_exception_dict)
# 使用
from kunpengException import UserDefineException, exist_exception_dict

body = {}


if not body:
    UserDefineException('Nobody11','body不能为空')# para: 异常类名,msg



print('
 except_dict 字典:',exist_exception_dict )
原文地址:https://www.cnblogs.com/dingyunfeng/p/13022927.html