简体   繁体   English

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

[英]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.

相关问题 使用请求获取页面而不是python中的源代码,为什么? 我怎样才能获得源代码? - use requests get page but not source code in python, why? how can i get source code? 如何使用 python 请求获取网络选项卡? - How can i get the network tab with python requests? 如何使用 python zeep 进行重试处理? 我正在使用请求重试 session,但未处理异常 - How do I get retry handling with python zeep? I'm using a requests retry session, but the exception is not handled 如何在Python中重用多个函数的异常处理代码? - How can I reuse exception handling code for multiple functions in Python? Python 请求:如何确定 MaxRetries 异常的响应代码 - Python requests: how to determine response code on MaxRetries exception 如何从python请求响应/异常对象访问对等方的证书链? - How can I access a peer's cert chain from a python-requests response/exception object? 我如何使用 python 请求登录 instagram - How can i login in instagram with python requests 如何在 python 中发布带有请求的有效负载? - How can I post payload with requests in python? 如何使用 python 请求登录网站? - How can i login to website with python requests? 如何获取python将字符串解释为python代码? - How can I get python to interpret a string as python code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM