-
Notifications
You must be signed in to change notification settings - Fork 0
/
customizer.py
71 lines (52 loc) · 2.52 KB
/
customizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from collections import defaultdict
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import HTTPException, RequestValidationError
from fastapi.responses import JSONResponse
def validation_body_exception_handler(app: FastAPI) -> callable:
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
try:
raw_err = exc.raw_errors
error_wrapper = raw_err[0]
validation_error = error_wrapper.exc
overwritten_errors = validation_error.errors()
resp = {"code": 422, "msg": "Unprocessable Entity", "errors": {}}
for e in overwritten_errors:
resp["errors"][e["loc"][0]] = e["msg"]
return JSONResponse(status_code=422, content=jsonable_encoder(resp))
except AttributeError as e:
rearranged_errors = defaultdict(list)
for pydantic_error in exc.errors():
loc, msg = pydantic_error["loc"], pydantic_error["msg"]
filtered_loc = loc[1:] if loc[0] in ("body", "query", "path") else loc
field_string = ".".join(filtered_loc) # nested fields with dot-notation
rearranged_errors[field_string].append(msg)
resp = {"code": 422, "msg": "Unprocessable Entity", "errors": {}}
for k, v in rearranged_errors.items():
if k == "" or v == "":
resp = {
"code": 422,
"msg": "Please fill all the field",
}
return JSONResponse(status_code=422, content=jsonable_encoder(resp))
resp["errors"][k] = v[0]
return JSONResponse(status_code=422, content=jsonable_encoder(resp))
except Exception as e:
print(e)
resp = {
"code": 422,
"msg": "Please fill all the field",
}
return JSONResponse(status_code=422, content=jsonable_encoder(resp))
return validation_exception_handler
def http_customize_handler(app: FastAPI) -> callable:
@app.exception_handler(HTTPException)
async def http_exception_handler(
request: Request, exc: HTTPException
) -> JSONResponse:
resp = {"code": exc.status_code, "msg": exc.detail}
return JSONResponse(status_code=exc.status_code, content=jsonable_encoder(resp))
return http_exception_handler