Skip to main content

Lightweight exception handling decorators for Python

Project description

safecatch

Safecatch is a lightweight Python package that provides decorators for streamlined exception handling.

It helps reduce repetitive try/except boilerplate while keeping application logic focused and readable.

Safecatch is designed for:

  • graceful degradation,
  • expected failure handling,
  • resilience patterns,
  • and cleaner recovery logic.

Philosophy

Safecatch is not intended to silently hide unexpected bugs.

The package is built around one principle:

Catch only expected failures.

Good use cases:

  • network timeouts,
  • missing optional files,
  • API fallbacks,
  • transient failures,
  • non-critical parsing issues.

Bad use cases:

  • catching broad Exception,
  • suppressing programming bugs,
  • hiding production errors,
  • ignoring unexpected behavior.

Safecatch should improve resilience without sacrificing debuggability.


Features

  • safecatch_handler

    • Catch a specific exception
    • Return a fallback value
    • Or execute a fallback function
  • multi_safecatch_handler

    • Handle multiple exception types
    • Use different recovery strategies per exception
  • Lightweight and dependency-free

  • Designed for readable recovery logic


Installation

pip install safecatch

Usage

Single Exception Handling

Use safecatch_handler to catch a single expected exception and provide a fallback value or fallback function.

from safecatch.safecatch import safecatch_handler

@safecatch_handler(ZeroDivisionError, 0)
def divide(a, b):
    return a / b

print(divide(10, 2))  # 5.0
print(divide(10, 0))  # 0

Using a Fallback Function

Fallback functions allow custom recovery behavior.

from safecatch.safecatch import safecatch_handler

def fallback_division(a, b):
    print("Division by zero occurred")
    return 0

@safecatch_handler(ZeroDivisionError, fallback_division)
def divide(a, b):
    return a / b

print(divide(10, 0))

Multiple Exception Handling

Use multi_safecatch_handler to define different recovery behavior for different exceptions.

from safecatch.multi_safecatch import multi_safecatch_handler

def handle_value_error(x, y):
    print(f"Invalid value detected: x={x}, y={y}")
    return -1

@multi_safecatch_handler({
    ZeroDivisionError: 0,
    ValueError: handle_value_error
})
def test_func(x, y):
    if y == 0:
        return x / y

    if y < 0:
        raise ValueError("Negative value")

    return x + y

print(test_func(3, 2))   # 5
print(test_func(3, 0))   # 0
print(test_func(3, -1))  # -1

Recommended Usage Patterns

Safecatch works best when handling:

  • expected operational failures,
  • recoverable errors,
  • external system instability.

Examples:

  • API request timeouts
  • Missing cache entries
  • Optional file loading
  • Temporary database connectivity issues
  • User-provided input parsing

Example:

from requests.exceptions import Timeout

@safecatch_handler(Timeout, {})
def fetch_user_data():
    return external_api_call()

Anti-Patterns

Avoid broad exception suppression.

Avoid This

@safecatch_handler(Exception, None)
def process_data():
    ...

This can:

  • hide programming bugs,
  • suppress critical failures,
  • make debugging difficult,
  • create silent production issues.

Prefer Specific Exceptions

@safecatch_handler(FileNotFoundError, [])
def load_optional_config():
    ...

Specific exception handling is safer and easier to debug.


Debugging and Observability

Safecatch should be used together with:

  • proper logging,
  • monitoring,
  • exception tracking tools.

Even when exceptions are intentionally handled, failures should remain observable.

Recommended tools:

  • logging
  • Sentry
  • OpenTelemetry
  • metrics dashboards

How It Works

Safecatch abstracts repetitive exception handling into reusable decorators.

Instead of repeatedly writing:

try:
    ...
except SomeError:
    ...

You define reusable recovery behavior once and apply it declaratively.


safecatch_handler

Takes:

  • an exception type,
  • and a fallback value or fallback function.

If the decorated function raises the specified exception:

  • the exception is intercepted,
  • and the fallback behavior is executed.

multi_safecatch_handler

Accepts a dictionary mapping:

  • exception types
  • to fallback values or fallback functions.

If an exception is raised:

  • the matching recovery behavior is executed,
  • otherwise the exception propagates normally.

Testing

Safecatch includes tests written with pytest.

Run tests locally:

pip install -e .
pip install -r tests/requirements.txt
pytest tests/

Contributing

Contributions are welcome.

Suggested areas for contribution:

  • logging support,
  • async support,
  • retry strategies,
  • observability integrations,
  • documentation improvements,
  • typing enhancements.

Please open an issue or submit a pull request on the GitHub repository.


Future Direction

Safecatch aims to evolve into a lightweight resilience and recovery utility for Python applications.

Planned areas of improvement include:

  • retry support,
  • async support,
  • telemetry and observability,
  • structured result objects,
  • production-safe exception handling patterns.

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

safecatch-1.0.4.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

safecatch-1.0.4-py3-none-any.whl (4.9 kB view details)

Uploaded Python 3

File details

Details for the file safecatch-1.0.4.tar.gz.

File metadata

  • Download URL: safecatch-1.0.4.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for safecatch-1.0.4.tar.gz
Algorithm Hash digest
SHA256 70edf4d075feeaa61fe6d9e0243db540e67257533013a8c80d69d735677ede8e
MD5 aab04d2c813fb92c8fb90b45036999ba
BLAKE2b-256 6f86f47b27c84c5751b60646dc68c5f0d0328ebce2867ad9166bffb9170490ef

See more details on using hashes here.

File details

Details for the file safecatch-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: safecatch-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 4.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for safecatch-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 0489507ef3873286a90d8ef04ccec161032bb8202b0cd9e13e1646921c0dfd4f
MD5 05395f1c0b1776218c4cbfbcad141b15
BLAKE2b-256 2a2450b08051a3f32cbec6be45e8afd94d62927db2285e38e79b753627125f8e

See more details on using hashes here.

Supported by

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