Skip to content

Commit

Permalink
feat(python): return JSON response with Internal Server Error for any…
Browse files Browse the repository at this point in the history
… exceptions

Part of #48
  • Loading branch information
php-coder committed Apr 22, 2024
1 parent ce0052a commit 9cd1318
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
10 changes: 9 additions & 1 deletion examples/python/fastapi/postgres/app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
from fastapi import FastAPI
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from routes import router

from custom_routes import router as custom_router

app = FastAPI()

@app.exception_handler(Exception)
async def exception_handler(request: Request, ex: Exception):
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"error": "Internal Server Error"}
)

app.include_router(router)

app.include_router(custom_router)
4 changes: 4 additions & 0 deletions examples/python/fastapi/postgres/custom_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@
@router.get('/custom/route')
def customRoute():
return { "custom": True }

@router.get('/custom/exception')
def customException():
raise RuntimeError('expected error')
10 changes: 9 additions & 1 deletion src/templates/app.py.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,22 @@ function removeExtension(filename) {
}
-%>
from fastapi import FastAPI
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from routes import router
<% customRouteFilenames.forEach(filename => { %>
from <%= removeExtension(filename) %> import router as <%= fileName2routerName(filename) %>
<% }) -%>

app = FastAPI()

@app.exception_handler(Exception)
async def exception_handler(request: Request, ex: Exception):
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"error": "Internal Server Error"}
)

app.include_router(router)
<% customRouteFilenames.forEach(filename => { %>
app.include_router(<%= fileName2routerName(filename) %>)
Expand Down

0 comments on commit 9cd1318

Please sign in to comment.