Python 2.7 Exception格式化工具

it2026-04-04  7

首先说一个发现:

1 try: 2 抛错误,抛异常 3 except Exception as e: 4 都被这里抓住了 5 except Error as e: 6 这里啥事都没了

然后,说说Exception as e的e。e可谓是格式五花八门。

比如:

再比如:

这么不严谨的格式,实在没办法直接从e.Name或e.Message等之类的主流方式来一步到位地抓出ErrorTitle与ErrorDetail。那怎么办呢?进行了各种尝试后,发现个好方法:

str(type(e)) 可以抓出Title,而且还包含Type。而str(e)则可以抓出Detail。

因此,诞生了格式化工具:

ExceptionX_Result.py:

1 class ExceptionX_Result: 2 exceptionType = None 3 exceptionTitle = None 4 exceptionDetail = None;

ExceptionX.py:

1 from ExceptionX_Result import ExceptionX_Result 2 3 class ExceptionX: 4 5 @staticmethod 6 def ToString(arg_exception) : 7 result = ExceptionX_Result 8 tempStr = str(type(arg_exception)) 9 tempStrArray = tempStr.split("'") 10 result.exceptionTitle = tempStrArray[1] 11 result.exceptionType = tempStrArray[0][1:] 12 result.exceptionDetail = str(arg_exception) 13 if result.exceptionDetail[0] == "<": 14 if result.exceptionDetail[result.exceptionDetail.__len__() - 1] == ">" : 15 result.exceptionDetail = result.exceptionDetail[1:result.exceptionDetail.__len__() - 1] 16 return result;

 

用法例子:

1 try: 2 value = 1 / 0 3 except Exception as e: 4 #在下面这行下一个断点,然后看看tempExceptionInfo的结构吧~ 5 tempExceptionInfo = ExceptionX.ToString(e)

 

呵呵,终于统一了。最终效果:

再如:

转载于:https://www.cnblogs.com/xxxteam/p/3515590.html

最新回复(0)