python请求:如何获取"异常代码"

时间:2015-01-04 05:12:09

标签: python exception

我正在使用"请求(2.5.1)" .now我想捕获异常并返回带有异常消息的dict,我将返回的dict如下:

{
   "status_code":   61, # exception code,
   "msg": "error msg",
}

但现在我无法获取错误status_code和错误消息,我尝试使用

try:
.....
except requests.exceptions.ConnectionError as e:
response={
            u'status_code':4040,
            u'errno': e.errno,
            u'message': (e.message.reason),
            u'strerror': e.strerror,
            u'response':e.response,
        }

但它过于冗余,我如何才能使错误信息变得简单?任何人都可以提出一些想法?

1 个答案:

答案 0 :(得分:0)

try:
    #the codes that you want to catch errors goes here
except:
    print ("an error occured.")

这将捕获所有错误,但更好的是你定义错误而不是捕获所有错误并打印特殊句子的错误。喜欢;

try:
    #the codes that you want to catch errors goes here
except SyntaxError:
    print ("SyntaxError occured.")
except ValueError:
    print ("ValueError occured.")
except:
    print ("another error occured.")

或者

try:
    #the codes that you want to catch errors goes here 
except Exception as t:
    print ("{} occured.".format(t))