Add a feature for custom exceptions and logs#246
Draft
karrtik159 wants to merge 3 commits intobenavlabs:mainfrom
Draft
Add a feature for custom exceptions and logs#246karrtik159 wants to merge 3 commits intobenavlabs:mainfrom
karrtik159 wants to merge 3 commits intobenavlabs:mainfrom
Conversation
…g middleware, and core application configuration.
Collaborator
|
Hey @karrtik159, I'll merge #240, and I'd like you to change your pr to be built on top of it, with the changes @sri-dhurkesh suggested on the issue #239. Thanks for the contribution |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Exception Middleware & Logging Implementation
A comprehensive exception handling and logging system for the FastAPI boilerplate with structured JSON responses and automatic error message translation.
Architecture Overview
flowchart TB subgraph Request Flow A[Incoming Request] --> B[CORS Middleware] B --> C[Client Cache Middleware] C --> D[Logging Middleware] D --> E[Exception Handler Middleware] E --> F[Route Handler] end subgraph Exception Handling F -->|ValidationError| G[setup_exception_handlers] F -->|HTTPException| G F -->|Generic Exception| E G --> H[get_friendly_message] H --> I[APIResponse Format] end subgraph Logging D -->|Log Request| J[Logger] I -->|Log Response| J J --> K[Console Handler] J --> L[File Handler + Rotation] endFiles Created
1. API Response Schema
File: api_response.py
Defines the standardized JSON response structure for all API endpoints.
Helper Functions:
2. Exception Handler Middleware
File: exception_handler_middleware.py
Handles all exceptions and converts them to the APIResponse format.
Key Components:
ERROR_MESSAGESdictError Message Translations:
Context-aware messages:
string_too_short+min_length: 8→"Must be at least 8 characters"string_too_long+max_length: 100→"Must be at most 100 characters"3. Logging Middleware
File: logging_middleware.py
Logs all incoming requests and outgoing responses with timing information.
Features:
X-Request-IDheader)X-Process-Timeheader)X-Forwarded-Forfor proxies)/health,/metrics)Log Format:
4. Enhanced Logger
File: logger.py
Centralized logging configuration with file rotation and colored console output.
Features:
RotatingFileHandlerfor automatic log rotation5. Logrotate Configuration
File: logrotate.conf
Production log rotation configuration for Linux systems.
Settings:
Files Modified
1. Configuration
File: config.py
Added LoggingSettings class:
2. Application Setup
File: setup.py
Changes in create_application():
Response Examples
Success Response (200)
{ "data": { "id": 1, "name": "User Userson", "email": "user@example.com" }, "isSuccess": true, "message": "User created successfully", "statusCode": 201 }Validation Error (422)
{ "data": [ { "field": "password", "message": "This field is required", "type": "missing" }, { "field": "email", "message": "Must be a valid email address", "type": "value_error.email" } ], "isSuccess": false, "message": "Validation failed", "statusCode": 422 }Not Found Error (404)
{ "data": null, "isSuccess": false, "message": "User not found", "statusCode": 404 }Server Error (500) - Debug Mode
{ "data": { "exception_type": "ValueError", "traceback": "Traceback (most recent call last):\n ..." }, "isSuccess": false, "message": "ValueError: Something went wrong", "statusCode": 500 }Configuration
Add to your
.envfile:Adding Custom Error Messages
To add more user-friendly messages, edit the
ERROR_MESSAGESdictionary in exception_handler_middleware.py:No changes to your Pydantic schemas are required!