Standardize API errors and structured logging - #53
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 98f0a2e8a3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return _error_response( | ||
| status_code=exc.status_code, | ||
| error_code=f"HTTP_{exc.status_code}", | ||
| message=str(exc.detail), | ||
| ) |
There was a problem hiding this comment.
Preserve WWW-Authenticate on auth failures
When protected endpoints raise HTTPException(..., headers={"WWW-Authenticate": "Bearer"}) from app/security.py or app/dependencies.py, this new handler rebuilds the response without passing through exc.headers. For example, an invalid bearer token on /api/v1/users/stats now returns a 401 with no WWW-Authenticate challenge, which breaks clients that rely on the header to recognize bearer-auth failures; include the original headers when creating the standardized response.
Useful? React with 👍 / 👎.
| @app.exception_handler(HTTPException) | ||
| async def http_exception_handler(request: Request, exc: HTTPException): |
There was a problem hiding this comment.
Handle Starlette HTTP exceptions too
Registering the handler only for FastAPI's HTTPException leaves framework-generated errors in the old shape because routing errors such as 404/405 are raised as starlette.exceptions.HTTPException. I checked an unknown route and it still returns {"detail":"Not Found"} instead of the standardized success/error envelope, so clients still see inconsistent error formats for missing paths or unsupported methods unless the handler is registered for Starlette's exception class as well.
Useful? React with 👍 / 👎.
Motivation
Description
AppExceptionexception handler that preserveserror_codeand returns the new standardized response shape via a shared helper_error_responseinapp/main.py.RequestValidationError), FastAPIHTTPException, and a global catch-all that all return the standardized JSON error object and log appropriate structured events.app/middleware/logging.py, defaulting to stdout and only attaching a file handler whenlog_fileis explicitly provided.RequestLoggingMiddlewareinapp/main.pyand clarifyAppException's doc/annotations inapp/utils/exceptions.py.tests/test_app_smoke.py, and update redirect/upgrade tests intests/test_redirect.pyandtests/test_users_upgrade.pyaccordingly.Testing
pytest -q; all tests passed.python -m flake8 app/main.py app/middleware/logging.py app/utils/exceptions.py tests/test_app_smoke.py tests/test_redirect.py tests/test_users_upgrade.py; checks passed.black,isort) were applied to updated files during the rollout.Codex Task