1+ import logging
12from collections .abc import Callable
23
34from fastapi import HTTPException
89
910from ..models .schemas .errors import ErrorGet
1011
12+ _logger = logging .getLogger (__file__ )
13+
1114
1215def create_error_json_response (* errors , status_code : int ) -> JSONResponse :
1316 # 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:
2023 return create_error_json_response (exc .detail , status_code = exc .status_code )
2124
2225
23- def make_http_error_handler_for_exception (
26+ def make_handler_for_exception (
2427 exception_cls : type [BaseException ],
2528 status_code : int ,
2629 * ,
27- detail_message : str ,
30+ error_message : str ,
2831 add_exception_to_message : bool = False ,
2932 add_oec_to_message : bool = False ,
3033) -> Callable :
@@ -35,13 +38,22 @@ def make_http_error_handler_for_exception(
3538 SEE https://docs.python.org/3/library/exceptions.html#concrete-exceptions
3639 """
3740
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
4145 if add_exception_to_message :
42- details += f"\n { error } "
46+ msg += f" { exception } "
47+
4348 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 )
4658
4759 return _http_error_handler
0 commit comments