[英]python requests: how can I get the “exception code”
I am using "requests (2.5.1)" .now I want to catch the exception and return an dict with some exception message,the dict I will return is as following: 我正在使用“ requests(2.5.1)”。现在我想捕获异常并返回带有一些异常消息的字典,我将返回的字典如下:
{
"status_code": 61, # exception code,
"msg": "error msg",
}
but now I can't get the error status_code and error message,I try to use 但是现在我无法获得错误的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,
}
but it's too redundancy,how can I get the error message simplicity?anyone can give some idea? 但是它太冗余了,如何使错误消息变得简单?有人可以提出想法吗?
try:
#the codes that you want to catch errors goes here
except:
print ("an error occured.")
This going to catch all errors, but better you define the errors instead of catching all of them and printing special sentences for errors.Like; 这样可以捕获所有错误,但是更好的是定义错误而不是捕获所有错误并为错误打印特殊句子。
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.")
Or; 要么;
try:
#the codes that you want to catch errors goes here
except Exception as t:
print ("{} occured.".format(t))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.