Errors¶
The helpers/errors subpackage turns exceptions into transport responses. capture, validation and mapping are
transport-agnostic; fastapi and grpc need the matching extra.
Capture¶
Capture exceptions: log them locally and record them on the active OpenTelemetry span.
archipy.helpers.errors.capture.logger
module-attribute
¶
archipy.helpers.errors.capture.capture_exception ¶
Captures an exception and records it on the current OpenTelemetry span.
Always logs locally. When OTel is enabled and a recording span is active,
records the exception event and sets span status via OtelUtils.status_for_exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
BaseException
|
The exception to capture and report. |
required |
Source code in archipy/helpers/errors/capture.py
Validation¶
Shared formatting and error mapping for validation failures.
archipy.helpers.errors.validation.SupportsErrors ¶
Bases: Protocol
A validation failure that lists its problems (pydantic and FastAPI request validation errors).
Source code in archipy/helpers/errors/validation.py
archipy.helpers.errors.validation.format_validation_errors ¶
format_validation_errors(
validation_error: SupportsErrors,
*,
include_type: bool = False,
include_input: bool = False,
) -> list[dict[str, str]]
Formats validation errors into a structured format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validation_error
|
SupportsErrors
|
The pydantic |
required |
include_type
|
bool
|
Whether to include the error type in the output. Defaults to False. |
False
|
include_input
|
bool
|
Whether to echo the rejected input value (as |
False
|
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
list[dict[str, str]]: A list of formatted validation error details. |
Source code in archipy/helpers/errors/validation.py
archipy.helpers.errors.validation.invalid_argument_from_validation ¶
Build the INVALID_ARGUMENT error that describes a request validation failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validation_error
|
ValidationError
|
The Pydantic validation error. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
InvalidArgumentError |
InvalidArgumentError
|
The error carrying the (input-free) validation details. |
Source code in archipy/helpers/errors/validation.py
archipy.helpers.errors.validation.request_validation ¶
Report a Pydantic ValidationError raised inside the block as INVALID_ARGUMENT.
The gRPC exception interceptor already reports every ValidationError as INVALID_ARGUMENT by default. Use this
context manager to mark the code that parses the client's request explicitly, which keeps that mapping when the
interceptor is created with validation_errors_as_internal=True.
Example
Raises:
| Type | Description |
|---|---|
InvalidArgumentError
|
When the block raises |
Source code in archipy/helpers/errors/validation.py
Mapping¶
Transport-agnostic mapping from any exception to the BaseError a client should see.
archipy.helpers.errors.mapping.resolve_error ¶
Return the BaseError to send to the client for error.
A BaseError passes through. A pydantic ValidationError becomes INVALID_ARGUMENT (the gRPC counterpart of
HTTP 422), or INTERNAL when validation_errors_as_internal is set. Anything else becomes a generic INTERNAL
error, so internals never reach the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
Exception
|
The exception raised by the handler. |
required |
validation_errors_as_internal
|
bool
|
Report a |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseError |
BaseError
|
The error to report. |
Source code in archipy/helpers/errors/mapping.py
FastAPI¶
FastAPI exception handlers that turn errors into JSON responses.
archipy.helpers.errors.fastapi.handlers.create_error_response ¶
Creates a standardized error response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
BaseError
|
The exception to be converted into a response. |
required |
capture
|
bool
|
Whether to log and record |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
A JSON response containing the exception details. |
Source code in archipy/helpers/errors/fastapi/handlers.py
archipy.helpers.errors.fastapi.handlers.validation_response ¶
Creates the 422 response for a validation failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
ValidationError | RequestValidationError
|
The pydantic or FastAPI request validation error. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
A 422 response listing the invalid fields. |
Source code in archipy/helpers/errors/fastapi/handlers.py
archipy.helpers.errors.fastapi.handlers.handle_fastapi_exception
async
¶
Handles a BaseError and returns its JSON response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_request
|
Request
|
The incoming request. |
required |
exception
|
BaseError
|
The exception to handle. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
A JSON response containing the exception details. |
Source code in archipy/helpers/errors/fastapi/handlers.py
archipy.helpers.errors.fastapi.handlers.handle_unexpected_exception
async
¶
Handles any other exception; the client only gets a generic error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_request
|
Request
|
The incoming request. |
required |
exception
|
Exception
|
The exception to handle. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
A JSON response holding the generic error. |
Source code in archipy/helpers/errors/fastapi/handlers.py
archipy.helpers.errors.fastapi.handlers.setup_exception_handlers ¶
Configures exception handlers for the FastAPI application.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
FastAPI
|
The FastAPI application instance. |
required |
Source code in archipy/helpers/errors/fastapi/handlers.py
OpenAPI documentation for the error responses of FastAPI routes.
archipy.helpers.errors.fastapi.openapi.get_fastapi_exception_responses ¶
get_fastapi_exception_responses(
exceptions: list[type[BaseError]],
) -> dict[int, dict[str, object]]
Generates OpenAPI response documentation for the given errors.
This method creates OpenAPI-compatible response schemas for FastAPI errors, including validation errors and custom errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exceptions
|
list[type[BaseError]]
|
A list of exception types to generate responses for. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict[str, object]]
|
dict[int, dict[str, object]]: A dictionary mapping HTTP status codes to their corresponding response schemas. |
Source code in archipy/helpers/errors/fastapi/openapi.py
DTOs describing error responses in the OpenAPI documentation.
archipy.helpers.errors.fastapi.response_dtos.FastAPIErrorResponseDTO ¶
Standardized error response model for OpenAPI documentation.
Source code in archipy/helpers/errors/fastapi/response_dtos.py
archipy.helpers.errors.fastapi.response_dtos.FastAPIErrorResponseDTO.status_code
instance-attribute
¶
archipy.helpers.errors.fastapi.response_dtos.FastAPIErrorResponseDTO.model
instance-attribute
¶
model: dict[str, object] = {
"description": exception.message_en,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": exception.code,
"description": "Error code identifier",
},
"detail": {
"type": "object",
"properties": detail_properties,
"required": [
"code",
"message_en",
"message_fa",
"http_status",
],
"additionalProperties": False,
"description": "Detailed error information",
},
},
}
}
},
}
archipy.helpers.errors.fastapi.response_dtos.ValidationErrorResponseDTO ¶
Bases: FastAPIErrorResponseDTO
Specific response model for validation errors.
Source code in archipy/helpers/errors/fastapi/response_dtos.py
archipy.helpers.errors.fastapi.response_dtos.ValidationErrorResponseDTO.status_code
instance-attribute
¶
archipy.helpers.errors.fastapi.response_dtos.ValidationErrorResponseDTO.model
instance-attribute
¶
model = {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "VALIDATION_ERROR",
"description": "Error code identifier",
},
"detail": {
"type": "array",
"items": {
"type": "object",
"properties": {
"field": {
"type": "string",
"example": "email",
"description": "Field name that failed validation",
},
"message": {
"type": "string",
"example": "Invalid email format",
"description": "Validation error message",
},
},
},
"example": [
{
"field": "email",
"message": "Invalid email format",
},
{
"field": "password",
"message": "Password must be at least 8 characters",
},
],
},
},
}
}
},
}
gRPC¶
Abort gRPC calls with the status and message of a BaseError.
archipy.helpers.errors.grpc.abort.grpc_status_code ¶
Convert an integer status (BaseError.grpc_status) to the gRPC StatusCode member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status
|
int
|
The integer gRPC status. |
required |
Returns:
| Type | Description |
|---|---|
StatusCode
|
grpc.StatusCode: The matching member, INTERNAL for an unknown integer. |
Source code in archipy/helpers/errors/grpc/abort.py
archipy.helpers.errors.grpc.abort.abort_grpc ¶
abort_grpc(
error: BaseError,
context: ServicerContext | ServicerContext | None,
) -> Awaitable[None] | None
Abort a gRPC call with the status code and message of error.
The context kind is detected automatically. On a sync context the call is aborted immediately. On an
grpc.aio context the abort is returned as an awaitable, so write await abort_grpc(error, context).
When error carries additional_data it is sent as the additional_data trailing metadata entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
BaseError
|
The error to report. |
required |
context
|
ServicerContext | ServicerContext | None
|
The sync or async gRPC servicer context to abort. |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[None] | None
|
Awaitable[None] | None: An awaitable for async contexts, None for sync contexts. |
Raises:
| Type | Description |
|---|---|
InvalidArgumentError
|
If the context is None or cannot be aborted. |
Source code in archipy/helpers/errors/grpc/abort.py
gRPC server interceptor for exception mapping.
archipy.helpers.errors.grpc.interceptors.GrpcExceptionInterceptor ¶
A gRPC server interceptor for centralized exception handling.
Catches the exceptions thrown by gRPC service methods and aborts the call with the matching gRPC status, so
service methods need no try/except blocks. BaseError keeps its own status, a pydantic ValidationError is
reported as INVALID_ARGUMENT (the counterpart of HTTP 422) and anything else as a generic INTERNAL error.
GrpcExceptionInterceptor() creates the sync interceptor and GrpcExceptionInterceptor(aio=True) the one for
grpc.aio servers.