-
Notifications
You must be signed in to change notification settings - Fork 63
refine exception handlers #216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from app.exception_handlers.registry import register_exception_handlers | ||
|
||
__all__ = ["register_exception_handlers"] |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import orjson | ||
from fastapi import Request | ||
from rotoger import AppStructLogger | ||
from attrs import define, field | ||
|
||
|
||
logger = AppStructLogger().get_logger() | ||
|
||
|
||
@define(slots=True) | ||
class RequestInfo: | ||
"""Contains extracted request information.""" | ||
path: str = field() | ||
body: dict = field(default=None) | ||
|
||
|
||
@define(slots=True) | ||
class BaseExceptionHandler: | ||
"""Base class for all exception handlers with common functionality.""" | ||
|
||
@staticmethod | ||
async def extract_request_info(request: Request) -> RequestInfo: | ||
"""Extract common request information.""" | ||
request_path = request.url.path | ||
request_body = None | ||
try: | ||
raw_body = await request.body() | ||
if raw_body: | ||
request_body = orjson.loads(raw_body) | ||
except orjson.JSONDecodeError: | ||
pass | ||
|
||
return RequestInfo(path=request_path, body=request_body) | ||
|
||
@classmethod | ||
async def log_error(cls, message: str, request_info: RequestInfo, **kwargs): | ||
"""Log error with standardized format.""" | ||
await logger.aerror( | ||
message, | ||
request_url=request_info.path, | ||
request_body=request_info.body, | ||
**kwargs | ||
) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
from fastapi import Request | ||
from fastapi.responses import JSONResponse | ||
from sqlalchemy.exc import SQLAlchemyError | ||
from app.exception_handlers.base import BaseExceptionHandler | ||
|
||
|
||
class SQLAlchemyExceptionHandler(BaseExceptionHandler): | ||
"""Handles SQLAlchemy database exceptions.""" | ||
|
||
@classmethod | ||
async def handle_exception(cls, request: Request, exc: SQLAlchemyError) -> JSONResponse: | ||
request_info = await cls.extract_request_info(request) | ||
|
||
await cls.log_error( | ||
"Database error occurred", | ||
request_info, | ||
sql_error=repr(exc) | ||
) | ||
|
||
return JSONResponse( | ||
status_code=500, | ||
content={"message": "A database error occurred. Please try again later."} | ||
) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
from fastapi import FastAPI | ||
from sqlalchemy.exc import SQLAlchemyError | ||
from fastapi.exceptions import ResponseValidationError | ||
|
||
from app.exception_handlers.database import SQLAlchemyExceptionHandler | ||
from app.exception_handlers.validation import ResponseValidationExceptionHandler | ||
|
||
def register_exception_handlers(app: FastAPI) -> None: | ||
"""Register all exception handlers with the FastAPI app.""" | ||
app.add_exception_handler(SQLAlchemyError, SQLAlchemyExceptionHandler.handle_exception) | ||
app.add_exception_handler(ResponseValidationError, ResponseValidationExceptionHandler.handle_exception) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
from fastapi import Request | ||
from fastapi.exceptions import ResponseValidationError | ||
from fastapi.responses import JSONResponse | ||
|
||
from app.exception_handlers.base import BaseExceptionHandler | ||
|
||
|
||
class ResponseValidationExceptionHandler(BaseExceptionHandler): | ||
"""Handles response validation exceptions.""" | ||
|
||
@classmethod | ||
async def handle_exception(cls, request: Request, exc: ResponseValidationError) -> JSONResponse: | ||
request_info = await cls.extract_request_info(request) | ||
errors = exc.errors() | ||
|
||
# Check if this is a None/null response case | ||
is_none_response = False | ||
for error in errors: | ||
if error.get("input") is None and "valid dictionary" in error.get("msg", ""): | ||
is_none_response = True | ||
break | ||
|
||
await cls.log_error( | ||
"Response validation error occurred", | ||
request_info, | ||
validation_errors=errors, | ||
is_none_response=is_none_response | ||
) | ||
|
||
if is_none_response: | ||
return JSONResponse( | ||
status_code=404, | ||
content={"no_response": "The requested resource was not found"} | ||
) | ||
else: | ||
return JSONResponse( | ||
status_code=422, | ||
content={"response_format_error": errors} | ||
) |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Exposing raw validation errors in the API response could leak internal implementation details. Consider sanitizing or formatting these errors for public consumption.
Copilot uses AI. Check for mistakes.