基于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就行了, 后期维护也只需维护异常模块, 而不需要去大量的翻阅代码
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现