|
8 | 8 | from typing import Any, Awaitable, Callable
|
9 | 9 |
|
10 | 10 | import sentry_sdk
|
11 |
| -from fastapi import FastAPI, Request, Response |
| 11 | +from fastapi import FastAPI, Request, Response, status |
| 12 | +from fastapi.encoders import jsonable_encoder |
| 13 | +from fastapi.exceptions import RequestValidationError |
| 14 | +from fastapi.responses import JSONResponse |
12 | 15 | from fastapi.staticfiles import StaticFiles
|
13 | 16 |
|
14 | 17 | from jbi.environment import get_settings, get_version
|
|
20 | 23 | settings = get_settings()
|
21 | 24 | version_info = get_version()
|
22 | 25 |
|
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
23 | 28 |
|
24 | 29 | def traces_sampler(sampling_context: dict[str, Any]) -> float:
|
25 | 30 | """Function to dynamically set Sentry sampling rates"""
|
@@ -75,7 +80,29 @@ async def request_summary(
|
75 | 80 | return response
|
76 | 81 | except Exception as exc:
|
77 | 82 | log_fields = format_request_summary_fields(
|
78 |
| - request, request_time, status_code=500 |
| 83 | + request, request_time, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR |
79 | 84 | )
|
80 | 85 | summary_logger.info(exc, extra=log_fields)
|
81 | 86 | raise
|
| 87 | + |
| 88 | + |
| 89 | +@app.exception_handler(RequestValidationError) |
| 90 | +async def validation_exception_handler( |
| 91 | + request: Request, exc: RequestValidationError |
| 92 | +) -> Response: |
| 93 | + """ |
| 94 | + Override the default exception handler for validation |
| 95 | + errors in order to log some information about malformed |
| 96 | + requests. |
| 97 | + """ |
| 98 | + logger.error( |
| 99 | + "invalid incoming request: %s", |
| 100 | + exc, |
| 101 | + extra={ |
| 102 | + "errors": exc.errors(), |
| 103 | + }, |
| 104 | + ) |
| 105 | + return JSONResponse( |
| 106 | + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, |
| 107 | + content={"detail": jsonable_encoder(exc.errors())}, |
| 108 | + ) |
0 commit comments