MCPcopy Create free account
hub / github.com/dbunt1tled/python-fast-api / exception_handler

Function exception_handler

src/api.py:100–141  ·  view source on GitHub ↗
(request: Request, e: Exception)

Source from the content-addressed store, hash-verified

98app.add_middleware(SlowAPIMiddleware)
99
100async def exception_handler(request: Request, e: Exception) -> JSONResponse:
101 di = Container()
102
103 req = {
104 "method": request.method,
105 "url": str(request.url),
106 "headers": filter_headers(request=request),
107 "ip": request.client.host if request.client else None,
108 "body": extract_body(request=request, secure=True),
109 }
110 if isinstance(e, ValueError):
111 di.log().error(message=f"ValueError: {e}", error=e.__dict__, request=req)
112 raise ValueError(e.args)
113
114 if isinstance(e, RequestValidationError):
115 error = ApiResponseService.format_pydantic_error(errors=e.errors())
116 di.log().error(message=f"RequestValidationError: {e}", error=str(error), request=req)
117 elif isinstance(e, DomainException):
118 e_data = e.as_dict()
119 if di.app_config().environment == Env.PRODUCTION:
120 e_data["source"] = None
121 error = JsonAPIService.response(errors=[e_data])
122 di.log().error(message=f"{e.__class__.__name__}: {e}", error=str(e_data), request=req)
123 else:
124 error = JsonAPIService.error(
125 status=500,
126 title="Internal Server Error",
127 detail=str(e),
128 code=str(ErrorNo.GENERAL_ERROR.value),
129 source={"traceback": traceback.format_exc()} if di.app_config().environment != Env.PRODUCTION else None,
130 )
131 di.log().error(message=f"{e.__class__.__name__}: {e}", error=str(error.model_dump()), request=req)
132 if error is None or error.errors is None:
133 di.log().error(message=f"{e.__class__.__name__}: {e}", error=None, request=req)
134 return JSONResponse(
135 status_code=500,
136 content={"status": 500, "title": "Internal Server Error", "detail": str(e)},
137 )
138 return JSONResponse(
139 status_code=error.errors[0]["status"],
140 content=error.model_dump(exclude_none=True),
141 )
142
143
144if RequestValidationError in app.exception_handlers:

Callers

nothing calls this directly

Calls 8

ContainerClass · 0.90
filter_headersFunction · 0.90
extract_bodyFunction · 0.90
format_pydantic_errorMethod · 0.80
as_dictMethod · 0.80
errorMethod · 0.45
logMethod · 0.45
responseMethod · 0.45

Tested by

no test coverage detected