Skip to content

Commit 409f6e8

Browse files
committed
feat: Add error handling
1 parent 4f1826a commit 409f6e8

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

app/main.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
from fastapi import FastAPI
2+
from fastapi.exceptions import RequestValidationError, ValidationError
3+
4+
from json import loads
25

36
from starlette.middleware.cors import CORSMiddleware
7+
from starlette.responses import JSONResponse
48

59
from app.router import api_router
610

11+
from app.utils.json_encoder import JSONEncoder
12+
713

814
description = 'A simple backend for dependency extraction'
915

@@ -22,6 +28,16 @@
2228
},
2329
)
2430

31+
@app.exception_handler(RequestValidationError)
32+
@app.exception_handler(ValidationError)
33+
async def validation_exception_handler(_ , exc):
34+
exc_json = loads(exc.json())
35+
response = {'message': []}
36+
for error in exc_json:
37+
response['message'].append(error['loc'][-1]+f": {error['msg']}")
38+
39+
return JSONResponse(content = JSONEncoder().encode(response), status_code = 422)
40+
2541
# Set all CORS enabled origins
2642
app.add_middleware(
2743
CORSMiddleware,

0 commit comments

Comments
 (0)