5
5
import starlette .exceptions
6
6
import starlette .responses
7
7
import starlette .status
8
+ from starlette .exceptions import HTTPException as StarletteHTTPException
8
9
9
10
from app .core .request_context import RequestContext
10
11
@@ -19,9 +20,9 @@ def build_error_response(
19
20
body = {
20
21
"status_code" : status_code ,
21
22
"message" : message ,
23
+ "request_id" : RequestContext .get_request_id (),
22
24
}
23
25
body .update (kwargs )
24
- body ["request_id" ] = RequestContext .get_request_id ()
25
26
return fastapi .responses .JSONResponse (body , status_code = status_code )
26
27
27
28
@@ -32,7 +33,7 @@ def setup_error_handlers(app: fastapi.FastAPI):
32
33
async def _value_error_handler (
33
34
_ : fastapi .Request , exc : ValueError
34
35
) -> fastapi .responses .JSONResponse :
35
- _logger .exception (exc )
36
+ _logger .error (exc )
36
37
return build_error_response (
37
38
status_code = starlette .status .HTTP_400_BAD_REQUEST ,
38
39
message = str (exc ),
@@ -50,16 +51,14 @@ async def _internal_server_error_handler(
50
51
async def _internal_http_exception_handler (
51
52
_ : fastapi .Request , exc : fastapi .HTTPException
52
53
) -> fastapi .responses .JSONResponse :
53
- _logger .exception (exc )
54
+ _logger .error (exc )
54
55
return build_error_response (
55
56
status_code = exc .status_code ,
56
57
message = exc .detail ,
57
58
)
58
59
59
60
app .add_exception_handler (ValueError , _value_error_handler )
60
- app .add_exception_handler (Exception , _internal_server_error_handler )
61
61
# Override starlette.exceptions.HTTPException response with our handler. Noe that fastapi.HTTPException inherits
62
62
# from starlette.exceptions.HTTPException. See https://fastapi.tiangolo.com/tutorial/handling-errors
63
- app .add_exception_handler (
64
- starlette .exceptions .HTTPException , _internal_http_exception_handler
65
- )
63
+ app .add_exception_handler (StarletteHTTPException , _internal_http_exception_handler )
64
+ app .add_exception_handler (Exception , _internal_server_error_handler )
0 commit comments