Skip to content

Exception handle decorator

Roberto Prevato edited this page Sep 21, 2019 · 1 revision

A decorator that wraps a given function to catch all exceptions that might happen during its execution, and re-throw new exceptions of the given type.

import pytest
from pytest import raises
from . import CrashTest
from essentials.decorators import exception_handle


class DesiredExceptionWithContext(Exception):
    """Example exception"""


def test_exception_handle():

    @exception_handle(DesiredExceptionWithContext)
    def crashing():
        raise CrashTest()

    with raises(DesiredExceptionWithContext) as captured_exception:
        crashing()

    assert str(captured_exception.value) == str(CrashTest())
Clone this wiki locally