python请求:我如何获得;例外代码“;

python请求:我如何获得;例外代码“;,python,exception,Python,Exception,我正在使用“requests(2.5.1)”。现在我想捕获异常并返回一个带有异常消息的dict,我将返回的dict如下所示: { "status_code": 61, # exception code, "msg": "error msg", } 但是现在我无法获取错误状态代码和错误消息,我尝试使用 try: ..... except requests.exceptions.ConnectionError as e: response={ u'statu

我正在使用“requests(2.5.1)”。现在我想捕获异常并返回一个带有异常消息的dict,我将返回的dict如下所示:

{
   "status_code":   61, # exception code,
   "msg": "error msg",
}
但是现在我无法获取错误状态代码和错误消息,我尝试使用

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,
        }
但是它太冗余了,我怎样才能得到简单的错误消息?任何人都可以给出一些想法吗

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.")


现在还不清楚你想做什么。您共享的代码有什么多余之处?我想捕获不同类型的异常并获取异常的原因,然后返回dict,因此如果有人调用我的函数,它将显示请求失败的原因。。对不起,我的英语不好。您可以在元组中捕获一组异常,如
except(ConnectionError,ValueError,indexer)as e
,然后在该块中,在dict中查找类型并返回自定义状态代码(“返回自定义状态代码”),因此请求没有自己的异常状态代码?如果这样,我知道怎么做,就像@NoMorePuppies anwsered…仍然感谢你可以做
响应。为状态提升\u
或类似的东西,当有非200响应状态代码时,它会抛出异常。
try:
    #the codes that you want to catch errors goes here 
except Exception as t:
    print ("{} occured.".format(t))