diff --git a/examples/python/fastapi/postgres/app.py b/examples/python/fastapi/postgres/app.py index 773f1c9..8c04ac2 100644 --- a/examples/python/fastapi/postgres/app.py +++ b/examples/python/fastapi/postgres/app.py @@ -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) diff --git a/examples/python/fastapi/postgres/custom_routes.py b/examples/python/fastapi/postgres/custom_routes.py index 5bf9232..217571c 100644 --- a/examples/python/fastapi/postgres/custom_routes.py +++ b/examples/python/fastapi/postgres/custom_routes.py @@ -6,3 +6,7 @@ @router.get('/custom/route') def customRoute(): return { "custom": True } + +@router.get('/custom/exception') +def customException(): + raise RuntimeError('expected error') diff --git a/src/templates/app.py.ejs b/src/templates/app.py.ejs index d379863..a1eb08d 100644 --- a/src/templates/app.py.ejs +++ b/src/templates/app.py.ejs @@ -11,7 +11,8 @@ 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) %> @@ -19,6 +20,13 @@ from <%= removeExtension(filename) %> import router as <%= fileName2routerName(f 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) %>)