def convert_exception(from_exception, to_exception, *to_args, **to_kw):
def wrapper(fn):<EOL><INDENT>def fn_new(*args, **kw):<EOL><INDENT>try:<EOL><INDENT>return fn(*args, **kw)<EOL><DEDENT>except from_exception:<EOL><INDENT>new_exception = to_exception(*to_args, **to_kw)<EOL>traceback = sys.exc_info()[<NUM_LIT:2>]<EOL>if PY3:<EOL><INDENT>value = new_exception<EOL><DEDENT>else:<EOL><INDENT>value = None<EOL><DEDENT>reraise(new_exception, value, traceback)<EOL><DEDENT><DEDENT>fn_new.__doc__ = fn.__doc__<EOL>return fn_new<EOL><DEDENT>return wrapper<EOL>
Decorator: Catch exception ``from_exception`` and instead raise ``to_exception(*to_args, **to_kw)``.

Useful when modules you're using in a method throw their own errors that you want to
convert to your own exceptions that you handle higher in the stack.

Example: ::

    class FooError(Exception):
        pass

    class BarError(Exception):
        def __init__(self, message):
            self.message = message

    @convert_exception(FooError, BarError, message='bar')
    def throw_foo():
        raise FooError('foo')

    try:
        throw_foo()
    except BarError as e:
        assert e.message == 'bar'