[Python-ideas] Let try-except check the exception instance

Ken Hilton kenlhilton at gmail.com
Thu May 31 10:26:42 EDT 2018


In one of my own packages, I use the following to catch dynamic error
messages:

    def handle_error(exc):
        # do stuff with exc
    with catch('error_code', handle_error):
        # do stuff that can raise an error

The definition of "catch" is as follows, assuming the root exception
actually raised is called "CodedError" whose "code" attribute is the error
code:

    from contextlib import contextmanager
    @contextmanager
    def catch(code=None, caught=None, always=None):
        try:
            yield
        except CodedError as exc:
            if isinstance(code, str):
                is_caught = exc.code == code
            else:
                is_caught = exc.code in code #assume it's a container
            if (code is not None) and not is_caught:
                raise
            if caught is not None:
                caught(exc)
        finally:
            if always is not None:
                always()

Perhaps you could make use of this?

Suggesting,
Ken Hilton;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180531/8926cb7c/attachment.html>


More information about the Python-ideas mailing list