Skip to content

Commit

Permalink
task: update error handlers, add request_id to error response, log st…
Browse files Browse the repository at this point in the history
…acktrace only on unknown exceptions
  • Loading branch information
svaponi committed Aug 30, 2024
1 parent 986e4fb commit f6afc17
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/app/core/error_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import starlette.exceptions
import starlette.responses
import starlette.status
from starlette.exceptions import HTTPException as StarletteHTTPException

from app.core.request_context import RequestContext

Expand All @@ -19,9 +20,9 @@ def build_error_response(
body = {
"status_code": status_code,
"message": message,
"request_id": RequestContext.get_request_id(),
}
body.update(kwargs)
body["request_id"] = RequestContext.get_request_id()
return fastapi.responses.JSONResponse(body, status_code=status_code)


Expand All @@ -32,7 +33,7 @@ def setup_error_handlers(app: fastapi.FastAPI):
async def _value_error_handler(
_: fastapi.Request, exc: ValueError
) -> fastapi.responses.JSONResponse:
_logger.exception(exc)
_logger.error(exc)
return build_error_response(
status_code=starlette.status.HTTP_400_BAD_REQUEST,
message=str(exc),
Expand All @@ -50,16 +51,14 @@ async def _internal_server_error_handler(
async def _internal_http_exception_handler(
_: fastapi.Request, exc: fastapi.HTTPException
) -> fastapi.responses.JSONResponse:
_logger.exception(exc)
_logger.error(exc)
return build_error_response(
status_code=exc.status_code,
message=exc.detail,
)

app.add_exception_handler(ValueError, _value_error_handler)
app.add_exception_handler(Exception, _internal_server_error_handler)
# Override starlette.exceptions.HTTPException response with our handler. Noe that fastapi.HTTPException inherits
# from starlette.exceptions.HTTPException. See https://fastapi.tiangolo.com/tutorial/handling-errors
app.add_exception_handler(
starlette.exceptions.HTTPException, _internal_http_exception_handler
)
app.add_exception_handler(StarletteHTTPException, _internal_http_exception_handler)
app.add_exception_handler(Exception, _internal_server_error_handler)

0 comments on commit f6afc17

Please sign in to comment.