gpt4 book ai didi

python - 获取带有请求的错误消息的简短版本

转载 作者:太空宇宙 更新时间:2023-11-03 16:10:54 26 4
gpt4 key购买 nike

我正在使用请求,并且需要异常的简短描述,

try:
resp = requests.get(url)
except Exception, e:
data['error'] = str(e)

例如,对于连接错误,str(e) 变为 ('Connection aborted.', error(61, 'Connection Beenrejected'))

我只想检索Connection aborted. 部分。

根据Exception类的文档,e.strerror应该可以工作,但是print (e.strerror)显示

有什么想法吗?

最佳答案

Exception 类是所有用户定义异常的基类(推荐)。

此类继承了 BaseException,它具有 args属性。该属性定义如下:

args

The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.

如果错误消息在args[0]中,您可以尝试:

try:
resp = requests.get(url)
except Exception as e:
data['error'] = e.args[0]

您不是在谈论标准异常,因为 print (e.strerror) 应该引发 AttributeError

对于你的答案,你应该考虑这个问题的答案:Correct way to try/except using Python requests module?

所有请求异常都继承requests.exceptions.RequestException ,它继承IOError

关于IOError,文档说:

exception EnvironmentError

The base class for exceptions that can occur outside the Python system: IOError, OSError. When exceptions of this type are created with a 2-tuple, the first item is available on the instance’s errno attribute (it is assumed to be an error number), and the second item is available on the strerror attribute (it is usually the associated error message). The tuple itself is also available on the args attribute.

但是 RequestException 似乎不是用 2 元组创建的,因此 strerrorNone

编辑:添加一些示例:

如果出现 HTTPError,则原始消息位于 args[0] 中。请参阅 requests.models.Response.raise_for_status 中的代码示例:

if http_error_msg:
raise HTTPError(http_error_msg, response=self)

如果出现ConnectionError,则args[0] 包含原始错误。请参阅 requests.adapters.HTTPAdapter.send 中的示例:

except (ProtocolError, socket.error) as err:
raise ConnectionError(err, request=request)

对于 ProxyErrorSSLErrorTimeout 来说也是一样的:args[0] 包含原始错误。

...

浏览GitHub repo中的源代码.

一种解决方案可能是:

try:
resp = requests.get(url)
except requests.exceptions.HTTPError as e:
data['error'] = e.args[0]
except requests.exceptions.RequestException as e:
cause = e.args[0]
data['error'] = str(cause.args[0])

关于python - 获取带有请求的错误消息的简短版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com