Skip to content

Reference: core

The public symbols of the core layer. Imported from the package root:

from fastapi_typed_errors import BaseError, ErrorResponse, error_models, handle_base_error

BaseError

fastapi_typed_errors.BaseError

BaseError(
    detail: str | None = None,
    *,
    headers: dict[str, str] | None = None,
)

Bases: HTTPException

Base class for typed HTTP errors.

A concrete subclass declares http_status and passes its error code as the generic parameter — everything else is derived by the metaclass. Plain string codes work too: BaseError[Literal["NOT_FOUND"]].

Example

::

class ErrorCode(StrEnum):
    NOT_FOUND = "NOT_FOUND"

class NotFoundError(BaseError[Literal[ErrorCode.NOT_FOUND]]):
    http_status = HTTPStatus.NOT_FOUND
    description = "Requested entity does not exist"

Attributes:

Name Type Description
http_status HTTPStatus

HTTP status the error responds with — the only required declaration in a subclass.

description str | None

Optional human-readable summary; used for OpenAPI status descriptions and as the default detail.

response_base type[ErrorResponse[Any]]

Generic response model the metaclass parametrizes; override to customize the response body.

error_code T

Error code extracted from the generic parameter; set by the metaclass.

model type[ErrorResponse[T]]

Response model parametrized with the error code; set by the metaclass.

Initialize the error.

Parameters:

Name Type Description Default
detail str | None

Human-readable explanation; defaults to description or the http_status phrase.

None
headers dict[str, str] | None

Extra HTTP headers for the response (e.g. WWW-Authenticate).

None

to_response

to_response() -> ErrorResponse[T]

Build the response body for this error instance.

Returns:

Type Description
ErrorResponse[T]

ErrorResponse[T]: An instance of model carrying error_code and detail.

ErrorResponse

fastapi_typed_errors.ErrorResponse

Bases: BaseModel

Error response body.

T is the Literal type of the error code — a StrEnum member or a plain string — so OpenAPI renders the exact value instead of the whole enum.

Attributes:

Name Type Description
code T

Machine-readable error code, narrowed to a Literal type.

detail str

Human-readable explanation of the error.

error_models

fastapi_typed_errors.error_models

error_models(
    e1: type[BaseError[C1]],
) -> type[ErrorResponse[C1]]
error_models(
    e1: type[BaseError[C1]], e2: type[BaseError[C2]]
) -> type[ErrorResponse[C1 | C2]]
error_models(
    e1: type[BaseError[C1]],
    e2: type[BaseError[C2]],
    e3: type[BaseError[C3]],
) -> type[ErrorResponse[C1 | C2 | C3]]
error_models(
    e1: type[BaseError[C1]],
    e2: type[BaseError[C2]],
    e3: type[BaseError[C3]],
    e4: type[BaseError[C4]],
) -> type[ErrorResponse[C1 | C2 | C3 | C4]]
error_models(
    e1: type[BaseError[C1]],
    e2: type[BaseError[C2]],
    e3: type[BaseError[C3]],
    e4: type[BaseError[C4]],
    e5: type[BaseError[C5]],
) -> type[ErrorResponse[C1 | C2 | C3 | C4 | C5]]
error_models(
    e1: type[BaseError[C1]],
    e2: type[BaseError[C2]],
    e3: type[BaseError[C3]],
    e4: type[BaseError[C4]],
    e5: type[BaseError[C5]],
    e6: type[BaseError[C6]],
) -> type[ErrorResponse[C1 | C2 | C3 | C4 | C5 | C6]]
error_models(
    e1: type[BaseError[C1]],
    e2: type[BaseError[C2]],
    e3: type[BaseError[C3]],
    e4: type[BaseError[C4]],
    e5: type[BaseError[C5]],
    e6: type[BaseError[C6]],
    e7: type[BaseError[C7]],
) -> type[ErrorResponse[C1 | C2 | C3 | C4 | C5 | C6 | C7]]
error_models(
    e1: type[BaseError[C1]],
    e2: type[BaseError[C2]],
    e3: type[BaseError[C3]],
    e4: type[BaseError[C4]],
    e5: type[BaseError[C5]],
    e6: type[BaseError[C6]],
    e7: type[BaseError[C7]],
    e8: type[BaseError[C8]],
) -> type[
    ErrorResponse[C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8]
]
error_models(
    *error_classes: type[BaseError[C]],
) -> type[ErrorResponse[C]]
error_models(
    *error_classes: type[BaseError[C]],
) -> type[ErrorResponse[C]]

Build a Pydantic model for the "model" key of a route's responses={}.

Parameters:

Name Type Description Default
*error_classes type[BaseError[C]]

BaseError subclasses to combine; repeated classes are deduplicated.

()

Returns:

Type Description
type[ErrorResponse[C]]

type[ErrorResponse[C]]: For a single class — its parametrized response model directly. For several classes — a discriminated union on the code field, which renders as a proper oneOf in OpenAPI.

Raises:

Type Description
TypeError

If called with no arguments, or if one error code is shared by multiple distinct response models (such a union cannot be discriminated).

handle_base_error

fastapi_typed_errors.handle_base_error async

handle_base_error(
    request: Request, error: Exception
) -> Response

Handle any BaseError raised inside a route or dependency.

Starlette resolves handlers by walking type(exc).__mro__, so this handler takes precedence over the default HTTPException handler for all BaseError subclasses while leaving plain HTTPException alone.

The error parameter is typed Exception to match Starlette's handler contract, keeping the registration line clean for every type checker; misregistration is caught at runtime instead.

Example

Register it explicitly, the FastAPI way::

app.add_exception_handler(BaseError, handle_base_error)

Parameters:

Name Type Description Default
request Request

Incoming request; unused, required by the handler signature.

required
error Exception

The raised error; must be a BaseError instance.

required

Returns:

Name Type Description
Response Response

JSON response built from error.to_response() with the error's HTTP status and headers.

Raises:

Type Description
TypeError

If the handler was registered for (and called with) an exception type that is not a BaseError subclass.

BaseErrorMeta

Public so metaclass conflicts can be resolved (see Customization); deliberately not re-exported from the root — import it from fastapi_typed_errors.core.base.

fastapi_typed_errors.core.base.BaseErrorMeta

Bases: type

Metaclass deriving error_code and model for BaseError subclasses.

When a concrete subclass is parametrized with a Literal code, the code is extracted from __orig_bases__ and written into the class namespace together with the parametrized response model — before type.__new__, so the metaclass properties below never shadow the stored values.

Public so that mixing BaseError with ABC (or another custom-metaclass base) can be resolved with a combined metaclass; deliberately not re-exported from the package root.

error_code property

error_code: str

Error code extracted from the generic parameter at class creation.

Returns:

Name Type Description
str str

The code declared via BaseError[Literal[<code>]].

Raises:

Type Description
AttributeError

If no class in the MRO declares a code.

model property

model: type[ErrorResponse[Any]]

Pydantic response model parametrized with the error code.

Returns:

Type Description
type[ErrorResponse[Any]]

type[ErrorResponse[Any]]: The parametrized subclass of response_base.

Raises:

Type Description
AttributeError

If no class in the MRO declares a code.