-
Notifications
You must be signed in to change notification settings - Fork 6
Implement structured error handling with custom exceptions #91
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
Open
tnederlof
wants to merge
1
commit into
main
Choose a base branch
from
feature/structured-error-handling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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,14 @@ | ||
| from .codes import ErrorCode | ||
| from .exceptions import AppError, BadRequestError, ConflictError, NotFoundError | ||
| from .handlers import register_exception_handlers | ||
| from .schemas import ErrorResponse | ||
|
|
||
| __all__ = [ | ||
| "ErrorCode", | ||
| "AppError", | ||
| "BadRequestError", | ||
| "ConflictError", | ||
| "NotFoundError", | ||
| "ErrorResponse", | ||
| "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,13 @@ | ||
| from enum import Enum | ||
|
|
||
|
|
||
| class ErrorCode(str, Enum): | ||
| CATEGORY_EXISTS = "CATEGORY_EXISTS" | ||
| CATEGORY_NOT_FOUND = "CATEGORY_NOT_FOUND" | ||
| PRODUCT_NOT_FOUND = "PRODUCT_NOT_FOUND" | ||
| IMAGE_NOT_FOUND = "IMAGE_NOT_FOUND" | ||
| VALIDATION_ERROR = "VALIDATION_ERROR" | ||
| BAD_REQUEST = "BAD_REQUEST" | ||
| NOT_FOUND = "NOT_FOUND" | ||
| CONFLICT = "CONFLICT" | ||
| INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR" |
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,70 @@ | ||
| from typing import Any | ||
| from .codes import ErrorCode | ||
|
|
||
|
|
||
| class AppError(Exception): | ||
| status_code: int | ||
| error_code: ErrorCode | ||
| message: str | ||
| details: dict[str, Any] | None | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| status_code: int, | ||
| error_code: ErrorCode, | ||
| message: str, | ||
| details: dict[str, Any] | None = None, | ||
| ) -> None: | ||
| self.status_code = status_code | ||
| self.error_code = error_code | ||
| self.message = message | ||
| self.details = details | ||
|
|
||
|
|
||
| class NotFoundError(AppError): | ||
| def __init__( | ||
| self, | ||
| *, | ||
| error_code: ErrorCode, | ||
| message: str, | ||
| details: dict[str, Any] | None = None, | ||
| ) -> None: | ||
| super().__init__( | ||
| status_code=404, | ||
| error_code=error_code, | ||
| message=message, | ||
| details=details, | ||
| ) | ||
|
|
||
|
|
||
| class BadRequestError(AppError): | ||
| def __init__( | ||
| self, | ||
| *, | ||
| error_code: ErrorCode, | ||
| message: str, | ||
| details: dict[str, Any] | None = None, | ||
| ) -> None: | ||
| super().__init__( | ||
| status_code=400, | ||
| error_code=error_code, | ||
| message=message, | ||
| details=details, | ||
| ) | ||
|
|
||
|
|
||
| class ConflictError(AppError): | ||
| def __init__( | ||
| self, | ||
| *, | ||
| error_code: ErrorCode, | ||
| message: str, | ||
| details: dict[str, Any] | None = None, | ||
| ) -> None: | ||
| super().__init__( | ||
| status_code=409, | ||
| error_code=error_code, | ||
| message=message, | ||
| details=details, | ||
| ) |
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,78 @@ | ||
| from fastapi import FastAPI, Request | ||
| from fastapi.responses import JSONResponse | ||
| from fastapi.exceptions import RequestValidationError | ||
| from starlette.exceptions import HTTPException as StarletteHTTPException | ||
| from .schemas import ErrorResponse | ||
| from .codes import ErrorCode | ||
| from .exceptions import AppError | ||
|
|
||
|
|
||
| def register_exception_handlers(app: FastAPI) -> None: | ||
| @app.exception_handler(AppError) | ||
| async def handle_app_error(request: Request, exc: AppError) -> JSONResponse: | ||
| body = ErrorResponse( | ||
| code=exc.status_code, | ||
| error_code=exc.error_code, | ||
| message=exc.message, | ||
| details=exc.details, | ||
| ) | ||
| return JSONResponse( | ||
| status_code=exc.status_code, | ||
| content=body.model_dump(), | ||
| ) | ||
|
|
||
| @app.exception_handler(RequestValidationError) | ||
| async def handle_validation_error( | ||
| request: Request, | ||
| exc: RequestValidationError, | ||
| ) -> JSONResponse: | ||
| errors = [] | ||
| for error in exc.errors(): | ||
| error_dict = dict(error) | ||
| if "ctx" in error_dict: | ||
| ctx = error_dict["ctx"] | ||
| if isinstance(ctx, dict): | ||
| for key, value in ctx.items(): | ||
| if isinstance(value, Exception): | ||
| ctx[key] = str(value) | ||
| error_dict["ctx"] = ctx | ||
| errors.append(error_dict) | ||
|
|
||
| details = {"errors": errors} | ||
| body = ErrorResponse( | ||
| code=422, | ||
| error_code=ErrorCode.VALIDATION_ERROR, | ||
| message="Validation error", | ||
| details=details, | ||
| ) | ||
| return JSONResponse(status_code=422, content=body.model_dump()) | ||
|
|
||
| @app.exception_handler(StarletteHTTPException) | ||
| async def handle_http_exception( | ||
| request: Request, | ||
| exc: StarletteHTTPException, | ||
| ) -> JSONResponse: | ||
| if exc.status_code == 404: | ||
| code = ErrorCode.NOT_FOUND | ||
| elif exc.status_code == 409: | ||
| code = ErrorCode.CONFLICT | ||
| elif 400 <= exc.status_code < 500: | ||
| code = ErrorCode.BAD_REQUEST | ||
| else: | ||
| code = ErrorCode.INTERNAL_SERVER_ERROR | ||
|
|
||
| body = ErrorResponse( | ||
| code=exc.status_code, | ||
| error_code=code, | ||
| message=str(exc.detail) if exc.detail else "Error", | ||
| ) | ||
| return JSONResponse(status_code=exc.status_code, content=body.model_dump()) | ||
|
|
||
| @app.exception_handler(Exception) | ||
| async def handle_unexpected(request: Request, exc: Exception) -> JSONResponse: | ||
| body = ErrorResponse( | ||
| code=500, | ||
| error_code=ErrorCode.INTERNAL_SERVER_ERROR, | ||
| message="Internal server error", | ||
| ) | ||
| return JSONResponse(status_code=500, content=body.model_dump()) | ||
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,10 @@ | ||
| from typing import Any | ||
| from pydantic import BaseModel | ||
| from .codes import ErrorCode | ||
|
|
||
|
|
||
| class ErrorResponse(BaseModel): | ||
| code: int | ||
| error_code: ErrorCode | ||
| message: str | ||
| details: dict[str, Any] | None = None |
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
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.
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.
The generic Exception handler silently swallows all unexpected errors without logging. This makes debugging production issues difficult. Consider adding logging before returning the generic error response: