Browse Source

Add an other example to exception handler for internal server errors

pull/13037/head
Hamid Afghan 4 months ago
committed by GitHub
parent
commit
ae6f937c7f
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 10
      docs_src/handling_errors/tutorial004.py

10
docs_src/handling_errors/tutorial004.py

@ -1,7 +1,9 @@
from fastapi import FastAPI, HTTPException from fastapi import FastAPI, HTTPException, status, Request
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
app = FastAPI() app = FastAPI()
@ -10,11 +12,17 @@ app = FastAPI()
async def http_exception_handler(request, exc): async def http_exception_handler(request, exc):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code) return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.exception_handler(status.HTTP_500_INTERNAL_SERVER_ERROR)
async def internal_exception_handler(request: Request, exc: Exception):
return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=jsonable_encoder({"message": "Internal Server Error"}))
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc): async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=400) return PlainTextResponse(str(exc), status_code=400)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=400)
@app.get("/items/{item_id}") @app.get("/items/{item_id}")
async def read_item(item_id: int): async def read_item(item_id: int):

Loading…
Cancel
Save