Exceptions & Centralized Error Handling
API reference for ZCore's domain exception hierarchy, HTTP status code mappings, sanitization helpers, and unified handler registration.
ZCore provides a unified exception hierarchy and a centralized normalization pipeline. When errors occur anywhere across services, repositories, schemas, or routing lifecycles, they are intercepted and rendered in the standard ResponseWrapper[None] JSON envelope.
Base Class: AppException
The root runtime exception for all custom business and domain errors in ZCore.
from zcore.exceptions import AppException
class AppException(Exception):
status_code: int = 500
def __init__(self, message: str, payload: dict | None = None) -> None:
super().__init__(message)
self.message = message
self.payload = payloadProp
Type
Built-In Domain Exceptions
ZCore provides pre-configured domain exceptions mapped to standard HTTP status codes:
from zcore.exceptions import (
AppException,
EntityNotFound,
DuplicateEntity,
ValidationError,
AuthError,
ForbiddenError
)Prop
Type
Unified Handler Registration: register_exception_handlers
Attaches all standardized exception normalization handlers to your FastAPI application in a single call, with granular boolean inclusion flags:
from zcore import register_exception_handlers
register_exception_handlers(app)Function Signature
def register_exception_handlers(
app: FastAPI,
include_app_exceptions: bool = True,
include_validation_exceptions: bool = True,
include_http_exceptions: bool = True,
include_response_validation_exceptions: bool = True,
include_unhandled_exceptions: bool = True,
) -> None: ...Prop
Type
Core Handlers Reference
ZCore exports five specialized asynchronous handlers:
1. app_exception_handler
Intercepts any AppException, logs structured diagnostics via structlog, and returns a ZCoreJSONResponse matching exc.status_code.
2. request_validation_exception_handler
Intercepts RequestValidationError (422 errors) raised by FastAPI/Pydantic on invalid request bodies or query parameters. Sanitizes nested error tuples into readable dot-separated paths.
3. http_exception_handler
Intercepts StarletteHTTPException instances, mapping custom headers and exception details cleanly into the error envelope.
4. response_validation_exception_handler
Intercepts internal ResponseValidationError (500 errors). Masks sensitive schema details in production, revealing granular errors only when settings.DEBUG = True.
5. unhandled_exception_handler
Catch-all fallback handler for uncaught runtime exceptions. Records the full stack trace in structured logs while returning a safe, sanitized generic message in production.
Error Sanitization Helpers
ZCore formats complex Pydantic validation errors through internal sanitization utilities:
_format_error_location(loc): Converts Pydantic location tuples (e.g.("body", "items", 0, "title")) into clean dot-separated field paths ("body.items.0.title")._sanitize_error_item(err): Safely extractsfield,message,type, and stringifiedcontextfrom raw error dictionaries.
Standardized JSON Error Envelopes
Domain Exception (404 Not Found)
{
"success": false,
"message": "Task not found.",
"data": null,
"meta": {
"error_type": "EntityNotFound",
"payload": {
"task_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
}
}Request Validation Error (422 Unprocessable Entity)
{
"success": false,
"message": "Validation error on 'body.title': Field required",
"data": null,
"meta": {
"error_type": "RequestValidationError",
"errors": [
{
"field": "body.title",
"message": "Field required",
"type": "missing"
}
]
}
}Production Debug-Gating:
For 500-level errors (ResponseValidationError and generic Exception), detailed error messages and raw validation lists are only exposed in the JSON response if settings.DEBUG = True. In production, a safe generic message is returned to prevent sensitive system disclosures.