一旦读取,就无法读取urllib错误消息 [英] Cannot read urllib error message once it is read()
问题描述
我的问题是python urllib错误对象的错误处理。我无法读取错误消息,但仍将其完整保留在错误对象中,以备日后使用。
My problem is with error handling of the python urllib error object. I am unable to read the error message while still keeping it intact in the error object, for it to be consumed later.
response = urllib.request.urlopen(request) # request that will raise an error
response.read()
response.read() # is empty now
# Also tried seek(0), that does not work either.
这就是我打算如何使用它,但是当异常冒出来时, .read()
第二次为空。
So this how I intend to use it, but when the Exception bubbles up, the.read()
second time is empty.
try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
self.log.exception(err.read())
raise err
我尝试制作err对象的深层副本
I tried making a deepcopy of the err object,
import copy
try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
err_obj_copy = copy.deepcopy(err)
self.log.exception(
"Method:{}\n"
"URL:{}\n"
"Data:{}\n"
"Details:{}\n"
"Headers:{}".format(method, url, data, err_obj_copy.read(), headers))
raise err
但副本无法进行深度复制并引发错误-
TypeError:__init __()缺少5个必需的位置参数备注: url, code, msg, hdrs和 fp
。
but copy is unable to make a deepcopy and throws an error -
TypeError: __init__() missing 5 required positional arguments: 'url', 'code', 'msg', 'hdrs', and 'fp'
.
如何阅读错误消息,同时仍将其完整保留在对象中?
How do I read the error message, while still keeping it intact in the object?
我确实知道如何使用请求
来做到这一点,但是我受制于旧版代码,需要使其与 urllib
I do know how to do it using requests
, but I am stuck with legacy code and need to make it work with urllib
推荐答案
这就是我所做的。
首次读取错误时,请将其保存到这样的变量中: msg = response.read()。解码('utf8')
。然后,您可以使用该消息创建一个新的 HTTPError
实例,并将其传播。
When reading the error for the first time, save it to a variable like this: msg = response.read().decode('utf8')
. You can then create a new HTTPError
instance, with the message, and propagate it.
resp = urllib.request.urlopen(request)
msg = resp.read().decode('utf8')
self.log.exception(msg)
raise HTTPError(resp.url, resp.code, resp.reason, resp.headers, io.BytesIO(bytes(msg, 'utf8')))
这篇关于一旦读取,就无法读取urllib错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!