Error Handling Strategy
Relevant source files
The following files were used as context for generating this wiki page:
The Error Handling Strategy in the Dev-Template repository is designed to provide a unified, predictable, and robust mechanism for capturing, logging, and responding to failures across all layers of the application. By centralizing exception definitions and processing logic, the system ensures that internal implementation details are shielded from the end-user while providing developers with the necessary context for debugging.
The strategy relies on a hierarchical structure of custom exceptions, a dedicated middleware for catching unhandled errors in the HTTP request-response cycle, and utility functions for consistent logging and formatting of error messages.
Exception Hierarchy and Core Classes
The project utilizes a structured approach to defining exceptions to differentiate between client-side errors (e.g., validation failures) and server-side errors (e.g., database connection issues).
Custom Exception Base
The BaseAppException serves as the foundation for all application-specific errors. It includes attributes for an error code, a human-readable message, and optional metadata.
| Attribute | Type | Description |
|---|---|---|
status_code | int | The HTTP status code to return to the client. |
message | str | A descriptive message explaining the error. |
code | str | A unique string identifier for the error type. |
payload | dict | Additional context or metadata related to the error. |
Sources: src/core/exceptions.py:1-15
Derived Exception Types
Common specialized exceptions derived from BaseAppException include:
NotFoundException: Triggered when a requested resource does not exist (Status 404).ValidationException: Used for input validation failures (Status 422).AuthenticationException: Indicates identity verification failure (Status 401).
Sources: src/core/exceptions.py:20-45
Centralized Middleware Processing
To ensure that no exception goes unhandled, a global ExceptionMiddleware is implemented. This component intercepts all outgoing responses and catches any exceptions raised during the execution of a request.
The diagram above illustrates the interception of exceptions by the middleware layer to prevent application crashes and provide formatted feedback.
Sources: src/middleware/exception_middleware.py:10-30
Middleware Logic Flow
- Catch: Intercepts
BaseAppException, standardException, and HTTP exceptions. - Log: Records the stack trace and relevant request metadata using the
error_handlerutility. - Response: Constructs a JSON response body containing the
messageandcode.
Sources: src/middleware/exception_middleware.py:35-50, src/utils/error_handler.py:5-12
Error Logging and Reporting
The error_handler.py utility provides a standardized way to log errors. It integrates with the system logger to ensure that errors are categorized by severity levels (ERROR, CRITICAL).
The sequence shows how application logic offloads logging responsibilities to the utility class for consistent formatting.
Sources: src/utils/error_handler.py:15-25
Implementation in API Endpoints
Endpoints inherit from a BaseEndpoint that provides helper methods for raising consistent exceptions. This reduces boilerplate code and ensures that every endpoint follows the established strategy.
# Example of raising a standardized exception in an endpoint
if not resource:
raise NotFoundException(message="User not found", payload={"user_id": 123})
Sources: src/api/v1/endpoints/base.py:10-22, src/core/exceptions.py:25
Summary
The Error Handling Strategy in Dev-Template centralizes the management of failures through a custom exception hierarchy and a robust middleware layer. By utilizing these components, the project achieves a high degree of maintainability and provides a consistent interface for both internal developers and external API consumers. Key components include the BaseAppException for structure, ExceptionMiddleware for global catch-all logic, and error_handler for structured logging.