pythonカスタム例外クラスの使用、Exceptionの継承

1328 ワード

カスタム例外クラスはすべてBaseErrorから継承されます
import traceback


class BaseError(Exception):
    def __init__(self):
        self.err_msg = ''
        self.err_msg_detail = ''


class RequestParamsError(BaseError):
    def __init__(self, err_msg):
        self.err_msg = {'code': 70011, 'message': '      '}
        self.err_msg_detail = "      " + err_msg
        Exception.__init__(self, self.err_msg, self.err_msg_detail)


def try_test():
    x = "yuihdjs"
    try:
        y = int(x)
    except Exception as ep:
        raise RequestParamsError(str(ep))


if __name__ == "__main__":
    try:
        try_test()
    except BaseError as err: #        “     ”      
        print(err.err_msg['message'])
        print(err.err_msg_detail)
        print(str(traceback.format_exc())) #        
    except Exception as ep:#        “      ”      
        print(str(ep))
        print(str(traceback.format_exc()))

印刷は、要求パラメータエラー要求パラメータエラーinvalid literal for int()with base 10:‘yuihdjs’Traceback(most recent call last):File"D:/HtmlWorkSpace/my_test/module/webtest/test.py"、line 25,in try_test y = int(x) ValueError: invalid literal for int() with base 10: ‘yuihdjs’
During handling of the above exception, another exception occurred: