gpt4 book ai didi

python - 在我的异常中停止,而不是库代码

转载 作者:太空狗 更新时间:2023-10-29 20:16:41 25 4
gpt4 key购买 nike

我正在使用 Python 库 urllib 开发一个应用程序,有时由于无法访问 URL 而出现异常。

但是,异常被提升到标准库堆栈的近 6 层:

/home/user/Workspace/application/main.py in call(path)
11 headers={'content-type': 'application/json'},
12 data=b'')
---> 13 resp = urllib.request.urlopen(req) ####### THIS IS MY CODE
14 return json.loads(resp.read().decode('utf-8'))

/usr/lib/python3.4/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
159 else:
160 opener = _opener
--> 161 return opener.open(url, data, timeout)
162
163 def install_opener(opener):

/usr/lib/python3.4/urllib/request.py in open(self, fullurl, data, timeout)
461 req = meth(req)
462
--> 463 response = self._open(req, data)
464
465 # post-process response

/usr/lib/python3.4/urllib/request.py in _open(self, req, data)
479 protocol = req.type
480 result = self._call_chain(self.handle_open, protocol, protocol +
--> 481 '_open', req)
482 if result:
483 return result

/usr/lib/python3.4/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
439 for handler in handlers:
440 func = getattr(handler, meth_name)
--> 441 result = func(*args)
442 if result is not None:
443 return result

/usr/lib/python3.4/urllib/request.py in http_open(self, req)
1208
1209 def http_open(self, req):
-> 1210 return self.do_open(http.client.HTTPConnection, req)
1211
1212 http_request = AbstractHTTPHandler.do_request_

/usr/lib/python3.4/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1182 h.request(req.get_method(), req.selector, req.data, headers)
1183 except OSError as err: # timeout error
-> 1184 raise URLError(err)
1185 r = h.getresponse()
1186 except:

URLError: <urlopen error [Errno 111] Connection refused>

我通常在打开 %pdb 魔法的情况下在 ipython3 中运行代码,这样万一出现异常我可以立即检查它。但是为此,我必须向下访问堆栈 6 层才能找到我的代码。

我的应用程序崩溃是否可以直接指向我的代码?

最佳答案

我会去修改代码:

try:
resp = urllib.request.urlopen(req)

except Exception as e:
raise RuntimeError(e)

那样:

  • %pdb 将您带到您的代码处,
  • 原始异常被保留为“次要”异常的参数。

你也可以 monkeypatch urllib.request.urlopen() 函数:

class MonkeyPatchUrllib(object):
def __enter__(self):
self.__urlopen = urllib.request.urlopen
urllib.request.urlopen = self
def __exit__(self, exception_type, exception_value, traceback):
urllib.request.urlopen = self.__urlopen
def __call__(self, *args, **kwargs):
try:
return self.__urlopen(*args, **kwargs)
except Exception as e:
raise RuntimeError(e)

任何时候在上下文管理器范围内的 urlibopen() 调用中引发异常:

with MonkeyPatchUrllib():
#your code here

%pdb 将使您与代码仅相差 1 级。

[编辑]

使用 sys.exc_info() 可以保留原始异常的更详细的上下文(例如它的回溯)。

关于python - 在我的异常中停止,而不是库代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069323/

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