Is it possible to automatically break into the debugger when a exception is thrown?

前端 未结 6 536
栀梦
栀梦 2021-02-07 06:00

If ones catches an exception outside of the function it is originally thrown, ones loses access to the local stack. As a result one cannot inspect the values of the variables th

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 06:23

    I found what I was looking for in an answer to What is the simplest way of using Python pdb to inspect the cause of an unhandled exception?

    Wrap it with that:

    
    def debug_on(*exceptions):
        if not exceptions:
            exceptions = (AssertionError, )
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                try:
                    return f(*args, **kwargs)
                except exceptions:
                    pdb.post_mortem(sys.exc_info()[2])
            return wrapper
        return decorator
    

    Example:

    @debug_on(TypeError)
    def buggy_function()
        ....
        raise TypeError
    

提交回复
热议问题