Error Handling Decorator for Handlers

Wrap handler functions in a decorator that converts known exceptions into structured error results while letting unexpected errors propagate.

PythonResilience

Code

pythonsnippet
28 lines
import functools
from typing import Any, Callable, Dict, Tuple, Type, TypeVar

T = TypeVar("T")


def handle_errors(
    known: Tuple[Type[BaseException], ...],
) -> Callable[[Callable[..., T]], Callable[..., Any]]:
    def decorator(func: Callable[..., T]) -> Callable[..., Any]:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Dict[str, Any]:
            try:
                return {"ok": True, "value": func(*args, **kwargs)}
            except known as error:
                return {"ok": False, "error": str(error)}

        return wrapper

    return decorator


@handle_errors((ValueError, KeyError))
def parse_age(raw: str) -> int:
    age = int(raw)
    if age < 0:
        raise ValueError("age must be positive")
    return age

How it works

Count the functions handle_errors, decorator, wrapper and parse_age as the entire surface area of Error Handling Decorator for Handlers.

ValueError is the guard’s signal — thrown at the branch, before any partial work happens.

What comes back is a new object, not a reference to anything passed in.

Caveats

  • The guard age < 0 short-circuits the flow with an early raise when its condition holds.

Using it

The primary signature is def handle_errors( known: Tuple[Type[BaseException], ...], ) -> Callable[[Callable[..., T]], Callable[..., …

Import handle_errors from the file and call it — the rest of the code is implementation detail.

Key statements

return {"ok": True, "value": func(*args, **kwargs)}
return {"ok": False, "error": str(error)}
def parse_age(raw: str) -> int:
    age = int(raw)
    if age < 0:
        raise ValueError("age must be positive")
    return age

Interactive Tools for This Topic

FAQ

Does `handle_errors` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
How does the code behave when input is bad?
The code throws `ValueError` — the guard `age < 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `handle_errors`, `decorator`, `wrapper` at load time.