停止在我的例外,而不是库代码 [英] Stop at exception in my, not library code
问题描述
我正在使用Python库开发一个应用程序 urllib
,而且由于无法访问URL,有时候会出现异常。
I'm developing an app using a Python library urllib
and it is sometimes rising exceptions due to not being able to access an URL.
但是,异常已经升级到标准库堆栈中的近6个级别:
However, the exception is raised almost 6 levels into the standard library stack:
/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>
我通常在 ipython3
中运行代码%pdb
魔术打开,以防万一有异常,我可以立即检查它。但是为此,我必须将堆栈6级别下降到我的代码。
I usually run the code in ipython3
with the %pdb
magic turned on so in case there is an exception I can inspect it immediately. However for this I have to go down the stack 6 levels to get to my code.
可以直接使用我的应用程序崩溃指向我的代码吗?
Is it achievable that my app crashes pointing to my code directly?
推荐答案
我会去修改代码:
try:
resp = urllib.request.urlopen(req)
except Exception as e:
raise RuntimeError(e)
这样:
- %pdb将你移动到您的代码
- 原始异常作为次要异常的参数保留。
您还可以使用monkeypatch urllib.request.urlopen()
function:
You may also monkeypatch urllib.request.urlopen()
function:
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() / code>在上下文管理器范围内调用
Any time you have an exception raised in urlibopen()
call within the context manager scope:
with MonkeyPatchUrllib():
#your code here
%pdb将仅将您的代码移动一级。
%pdb will move you only 1 level away from your code.
使用 sys.exc_info()
可以保留更详细的原始异常上下文(如其追溯)。
With sys.exc_info()
it is possible to preserve a more verbose context of the original exception (like its traceback).
这篇关于停止在我的例外,而不是库代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!