基于Exception 开发自定义异常管理

前言

在项目开发中,经常会遇到各种各样的异常, 同时有需要对这些异常进行相应的捕获处理, 随着项目的推进,这样的捕获处理就会越来越多, 后期维护也越来越复杂,为了解决这个问题, 特别推荐使用异常管理

 

模块代码:

# -*- coding: utf-8 -*-

from exceptions import Exception


class BaseError(Exception):
    """
    异常类型基类;
    类属性 _code_and_description 用于自定义子类异常信息: {'code': 'message'}
    """
    _code_and_description = {}

    def __init__(self, code):
        if isinstance(code, int):
            code = str(code)
        self.code = code

    def __str__(self):
        if self._code_and_description.get(self.code):
            return '{}  {}'.format(self.code, self._code_and_description.get(self.code))
        else:
            print '错误code 和错误描述: {}'.format(self._code_and_description)
            return '未知的错误类型: %s' % self.code

    @staticmethod
    def code_and_description():
        """
        用于查询定义的异常code 与message 信息
        :return:
        """
        return BaseError._code_and_description




class TestItemError(BaseError):
    """
    test 检测项 相关报错
    """
    
    _code_and_description = {
        '1001': '老子到此一游',
        '2002': '庄子到此一游',
    }

    def __init__(self, *args):
        super(TestItemError, self).__init__(*args)
        BaseError._code_and_description = TestItemError._code_and_description


if __name__ == '__main__':
    try:
        raise TestItemError(1001)
    except TestItemError as e:
        print e
        print e.code

使用时只需引入模块, 在需要的地方抛出异常code就行了, 后期维护也只需维护异常模块, 而不需要去大量的翻阅代码

 

posted @ 2022-06-13 15:19  萤huo虫  阅读(31)  评论(0编辑  收藏  举报