1
+ import logging
1
2
from collections .abc import Callable
2
3
3
4
from fastapi import HTTPException
8
9
9
10
from ..models .schemas .errors import ErrorGet
10
11
12
+ _logger = logging .getLogger (__file__ )
13
+
11
14
12
15
def create_error_json_response (* errors , status_code : int ) -> JSONResponse :
13
16
# NOTE: do not forget to add in the decorator `responses={ ???: {"model": ErrorGet} }`
@@ -20,11 +23,11 @@ async def http_error_handler(_: Request, exc: HTTPException) -> JSONResponse:
20
23
return create_error_json_response (exc .detail , status_code = exc .status_code )
21
24
22
25
23
- def make_http_error_handler_for_exception (
26
+ def make_handler_for_exception (
24
27
exception_cls : type [BaseException ],
25
28
status_code : int ,
26
29
* ,
27
- detail_message : str ,
30
+ error_message : str ,
28
31
add_exception_to_message : bool = False ,
29
32
add_oec_to_message : bool = False ,
30
33
) -> Callable :
@@ -35,13 +38,22 @@ def make_http_error_handler_for_exception(
35
38
SEE https://docs.python.org/3/library/exceptions.html#concrete-exceptions
36
39
"""
37
40
38
- async def _http_error_handler (_ : Request , error : BaseException ) -> JSONResponse :
39
- assert isinstance (error , exception_cls ) # nosec
40
- details = detail_message
41
+ async def _http_error_handler (_ : Request , exception : BaseException ) -> JSONResponse :
42
+ assert isinstance (exception , exception_cls ) # nosec
43
+
44
+ msg = error_message
41
45
if add_exception_to_message :
42
- details += f"\n { error } "
46
+ msg += f" { exception } "
47
+
43
48
if add_oec_to_message :
44
- details += f"\n [OEC: { create_error_code (error )} ]"
45
- return create_error_json_response (details , status_code = status_code )
49
+ error_code = create_error_code (exception )
50
+ msg += f" [{ error_code } ]"
51
+ _logger .exception (
52
+ "Unexpected %s: %s" ,
53
+ exception .__class__ .__name__ ,
54
+ msg ,
55
+ extra = {"error_code" : error_code },
56
+ )
57
+ return create_error_json_response (msg , status_code = status_code )
46
58
47
59
return _http_error_handler
0 commit comments