Python 2.7 Exception格式化工具

首先说一个发现:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值