Python 自定义异常处理Error函数

本文介绍了一个Python程序中自定义异常处理的方法,包括错误代码及其含义、异常类定义及使用示例。通过对不同错误情况的捕获与处理,确保了程序运行的稳定性和健壮性。
部署运行你感兴趣的模型镜像

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-


CODEMSG = {
    2000: u"True",
    4000: u"客户上传的文件格式不正确",
    4010: u"客户上传的文件格式是要求格式以外的文件",
    4001: u"客户上传的文件列超过1024",
    4002: u"客户端未传值或值传递错误!",
    4003: u"文件数据格式不对",
    4004: u"已经存在",
    4005: u"用户未认证或认证不成功",
    4006: u"无法进行数据分析",
    4007: u"用户分析条件不正确",
    4008: u"用户无权限",
    4999: u"Unknown Error!!!",
    5000: u"服务器错误",
    5001: u"数据表已经存在",
    5002: u"sql语句错误",
    5003: u"索引文件未创建"
}


class MyCustomError(Exception):
    """
    Error class for the IBM SPSS Statistics Input Output Module
    Use Method:

    def example():
    try:
        raise ValueError # ['']
        raise SPSSError(retcode="6001") or  raise SPSSError(retcode=6001) or raise SPSSError
    except Exception as e:
        e = FormatErrorCode(e)
        print(e) # ['4999', 'Unknown Error!!!']

    example()

    #>>> (5001, '数据表已经存在')

    """

    def __init__(self, msg=None, retcode=4999):
        self.retcode = int(retcode)
        try:
            if not msg:
                msg = CODEMSG[int(self.retcode)]
        except:
            msg = "Unknown Error!!!"
        Exception.__init__(self, self.retcode, msg)


def FormatErrorCode(arg):
    data = str(arg).replace("(", "").replace(")", "").replace("'", '').split(",")
    if all(data):
        Error_Infor = [i.strip() for i in data if i]
        if len(Error_Infor) == 2:
            return [i.strip() for i in data if i]
        else:
            try:
                raise MyCustomError(msg=Error_Infor[0])
            except Exception as e:
                return FormatErrorCode(e)
    else:
        try:
            raise MyCustomError()
        except Exception as e:
            return FormatErrorCode(e)


class SPSSError(MyCustomError):
    def __init__(self, retcode=None):
        super(SPSSError, self).__init__(retcode=retcode)


class GetParametersError(MyCustomError):
    def __init__(self, retcode=4002):
        super(GetParametersError, self).__init__(retcode=retcode)


if __name__ == '__main__':
    from common.base import MyPymysql

    try:
        ret = MyPymysql('asdf')
        res = ret.selectall_sql('')
        ret.close()

        # raise ValueError # [''] -> ['4999', 'No section: asdf']
        raise GetParametersError() or raise GetParametersError(40088) or raise GetParameterError
    except Exception as e:
        print("Error is :", e)
        e = FormatErrorCode(e)
        print(e)

 

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值