Skip to main content

Helpers for handling Python errors

Project description

errorhelpers

PyPI version PyPI pyversions Maintainability Test Coverage

Helpers for handling Python errors.

Usage:

# As a decorator
@errorhelpers.expect_error(*errors, on_unexpected_error=handler)
def some_error_prone_funcion():
    ...

# Using with statement
with errorhelpers.expect_error(*errors, on_unexpected_error=handler):
    # Some error prone operation
    ...

Example 1: Basic usage

import pytest
import errorhelpers

with errorhelpers.expect_errors(ZeroDivisionError):
    assert 4 / 2 == 2

# `ZeroDivisionError` will be re-raised.
with pytest.raises(ZeroDivisionError):
    with errorhelpers.expect_errors(ZeroDivisionError):
        4 / 0

# In case of other exceptions, `errorhelpers.UnexpectedError("Unexpected error")`
# will be raised instead.
with pytest.raises(errorhelpers.UnexpectedError, match="Unexpected error"):
    with errorhelpers.expect_errors(ZeroDivisionError):
        "a" / "b"

Example 2: Custom error

import pytest
import errorhelpers

class CustomError(Exception):
    @classmethod
    def raise_(cls, msg):
        def raiser(error):
            print("Hiding error:", error)
            raise cls(msg)

        return raiser

@errorhelpers.expect_errors(
    ZeroDivisionError, on_unexpected_error=CustomError.raise_("Custom error")
)
def sensitive_transaction(x, y):
    return int(x) / int(y)

assert sensitive_transaction(4, "2") == 2

# `ZeroDivisionError` will be re-raised.
with pytest.raises(ZeroDivisionError):
    sensitive_transaction(4, 0)

# In case of other exceptions, `CustomError` will be raised instead.
with pytest.raises(CustomError, match="Custom error"):
    sensitive_transaction("a", "b")

# Hiding error: invalid literal for int() with base 10: 'a'

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

errorhelpers-0.2.0.tar.gz (3.5 kB view hashes)

Uploaded Source

Built Distribution

errorhelpers-0.2.0-py3-none-any.whl (3.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page