Stop at exception in my, not library code

后端 未结 5 2220
故里飘歌
故里飘歌 2021-02-14 22:33

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.

However, the exception is

5条回答
  •  滥情空心
    2021-02-14 23:27

    I would go with modifying the code:

    try:
        resp = urllib.request.urlopen(req)
    
    except Exception as e:
        raise RuntimeError(e)
    

    That way:

    • %pdb moves you to your code,
    • the original exception is preserved as argument of the "secondary" exception.

    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)
    

    Any time you have an exception raised in urlibopen() call within the context manager scope:

    with MonkeyPatchUrllib():
        #your code here
    

    %pdb will move you only 1 level away from your code.

    [EDIT]

    With sys.exc_info() it is possible to preserve a more verbose context of the original exception (like its traceback).

提交回复
热议问题