Skip to content

Commit 9cd1318

Browse files
committed
feat(python): return JSON response with Internal Server Error for any exceptions
Part of #48
1 parent ce0052a commit 9cd1318

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed
+9-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1-
from fastapi import FastAPI
1+
from fastapi import FastAPI, Request, status
2+
from fastapi.responses import JSONResponse
23
from routes import router
34

45
from custom_routes import router as custom_router
56

67
app = FastAPI()
78

9+
@app.exception_handler(Exception)
10+
async def exception_handler(request: Request, ex: Exception):
11+
return JSONResponse(
12+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
13+
content={"error": "Internal Server Error"}
14+
)
15+
816
app.include_router(router)
917

1018
app.include_router(custom_router)

examples/python/fastapi/postgres/custom_routes.py

+4
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,7 @@
66
@router.get('/custom/route')
77
def customRoute():
88
return { "custom": True }
9+
10+
@router.get('/custom/exception')
11+
def customException():
12+
raise RuntimeError('expected error')

src/templates/app.py.ejs

+9-1
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,22 @@ function removeExtension(filename) {
1111
}
1212
1313
-%>
14-
from fastapi import FastAPI
14+
from fastapi import FastAPI, Request, status
15+
from fastapi.responses import JSONResponse
1516
from routes import router
1617
<% customRouteFilenames.forEach(filename => { %>
1718
from <%= removeExtension(filename) %> import router as <%= fileName2routerName(filename) %>
1819
<% }) -%>
1920

2021
app = FastAPI()
2122

23+
@app.exception_handler(Exception)
24+
async def exception_handler(request: Request, ex: Exception):
25+
return JSONResponse(
26+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
27+
content={"error": "Internal Server Error"}
28+
)
29+
2230
app.include_router(router)
2331
<% customRouteFilenames.forEach(filename => { %>
2432
app.include_router(<%= fileName2routerName(filename) %>)

0 commit comments

Comments
 (0)