File tree 3 files changed +22
-2
lines changed
examples/python/fastapi/postgres
3 files changed +22
-2
lines changed Original file line number Diff line number Diff line change 1
- from fastapi import FastAPI
1
+ from fastapi import FastAPI , Request , status
2
+ from fastapi .responses import JSONResponse
2
3
from routes import router
3
4
4
5
from custom_routes import router as custom_router
5
6
6
7
app = FastAPI ()
7
8
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
+
8
16
app .include_router (router )
9
17
10
18
app .include_router (custom_router )
Original file line number Diff line number Diff line change 6
6
@router .get ('/custom/route' )
7
7
def customRoute ():
8
8
return { "custom" : True }
9
+
10
+ @router .get ('/custom/exception' )
11
+ def customException ():
12
+ raise RuntimeError ('expected error' )
Original file line number Diff line number Diff line change @@ -11,14 +11,22 @@ function removeExtension(filename) {
11
11
}
12
12
13
13
- %>
14
- from fastapi import FastAPI
14
+ from fastapi import FastAPI, Request, status
15
+ from fastapi.responses import JSONResponse
15
16
from routes import router
16
17
<% customRouteFilenames .forEach (filename => { % >
17
18
from < %= removeExtension (filename) % > import router as <%= fileName2routerName(filename) %>
18
19
< % }) - %>
19
20
20
21
app = FastAPI()
21
22
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
+
22
30
app.include_router(router)
23
31
<% customRouteFilenames .forEach (filename => { % >
24
32
app .include_router (< %= fileName2routerName (filename) % > )
You can’t perform that action at this time.
0 commit comments