最新消息:20210917 已从crifan.com换到crifan.org

[已解决]Python中如何获取捕获的异常的详细信息

Python crifan 2348浏览 0评论

代码中,之前在别处抛出异常:

    def _check_official_error(self, json_data):
        “””
        检测微信公众平台返回值中是否包含错误的返回码
        :raises OfficialAPIError: 如果返回码提示有错误,抛出异常;否则返回 True
        “””
        if ‘errcode’ in json_data and json_data[‘errcode’] != 0:
            raise OfficialAPIError(errcode=json_data.get(‘errcode’), errmsg=json_data.get(‘errmsg’, ”))
class OfficialAPIError(WechatAPIException):
    “””微信官方API请求出错异常”””
    def __init__(self, errcode, errmsg=None):
        if errmsg is None:  # 对旧版本 OfficialAPIError 的兼容代码
            super(OfficialAPIError, self).__init__(99999, errmsg=errcode)
            return
        super(OfficialAPIError, self).__init__(errcode, errmsg)

此处去捕获:

try:
    userInfoDict = wechat.get_user_info(curUserOpenid)
except OfficialAPIError:
    userInfoDict = {}
    gLog.error(“error”)

但是不支持如何获得对应的error的实例,

无法获得error的详细信息

python try except error message

HandlingExceptions – Python Wiki

8. Errors and Exceptions — Python 3.5.2 documentation

->

except OSError as err:
    print(“OS error: {0}”.format(err))

然后用代码:

        try:
            userInfoDict = wechat.get_user_info(curUserOpenid)
        except OfficialAPIError as apiError:
            userInfoDict = {}
            gLog.error(“apiError=%s”, apiError)

即可输出错误异常时候的信息:

apiError=40003: invalid openid hint: [OmbrLA0991vr18]

[总结]

对于:

        try:
            …
        except SomeTypeError:
            …

是可以捕获异常的。

而想要得到异常的信息时,可以:

        try:
            …
        except SomeTypeError as someError:
           print someError

[后记]

参考:

python exception message capturing – Stack Overflow

-》想要捕获处理所有类型的异常的信息,可以用:

Exception

其中此处的异常类型,果然其基类,都是Exception

class WechatException(Exception):
    “””wechat-python-sdk 异常基类”””
    pass
class WechatAPIException(WechatException):
    “””官方 API 错误异常(必须包含错误码及错误信息)”””
    def __init__(self, errcode, errmsg):
        “””
        :param errcode: 错误代码
        :param errmsg: 错误信息
        “””
        self.errcode = errcode
        self.errmsg = errmsg
    def __str__(self):
        if six.PY2:
            return to_binary(‘{code}: {msg}’.format(code=self.errcode, msg=self.errmsg))
        else:
            return to_text(‘{code}: {msg}’.format(code=self.errcode, msg=self.errmsg))
class OfficialAPIError(WechatAPIException):
    “””微信官方API请求出错异常”””
    def __init__(self, errcode, errmsg=None):
        if errmsg is None:  # 对旧版本 OfficialAPIError 的兼容代码
            super(OfficialAPIError, self).__init__(99999, errmsg=errcode)
            return
        super(OfficialAPIError, self).__init__(errcode, errmsg)

-》所以此处如果处理了Exception,则上述所有类型的异常都可以捕获了

-》可以避免只处理了一种异常,而出现其它异常,程序还是会挂掉

结果好像用:

except Exception, someError:

语法上有问题

所以改为:

except Exception as someError:

代码:

        try:
            userInfoDict = wechat.get_user_info(curUserOpenid)
        #except OfficialAPIError as apiError:
        except Exception as someError:
            # when not set valid access token will case this error
            userInfoDict = {}
            gLog.error(“someError=%s”, someError)
            # someError=40003: invalid openid hint: [OmbrLA0991vr18]

输出:

someError=40003: invalid openid hint: [g9g9ja0886vr22]

[总结2]

想要捕获所有类型的异常,则可以用异常的基类:

except Exception as someError:

就可以获取异常的信息了。

[后记3]

如果此处通过log.exception而不是log.error的话:

gLog.exception(“someError=%s”, someError)

则除了会打印error信息之外,还会报告异常:

ERROR in views [/root/html/SIPEvents/sipevents/views.py:166]:
someError=40003: invalid openid hint: [1mqSHa0081vr18]

<div–<——————————————————————————

Traceback (most recent call last):
  File “/root/html/SIPEvents/sipevents/views.py”, line 161, in getUserInfo
    userInfoDict = wechat.get_user_info(curUserOpenid)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/basic.py”, line 645, in get_user_info
    ‘lang’: lang,
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/request.py”, line 89, in get
    **kwargs
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/request.py”, line 74, in request
    self._check_official_error(response_json)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/request.py”, line 113, in _check_official_error
    raise OfficialAPIError(errcode=json_data.get(‘errcode’), errmsg=json_data.get(‘errmsg’, ”))
OfficialAPIError: 40003: invalid openid hint: [1mqSHa0081vr18]

转载请注明:在路上 » [已解决]Python中如何获取捕获的异常的详细信息

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
99 queries in 0.253 seconds, using 23.36MB memory