diff --git a/docs_src/handling_errors/tutorial004.py b/docs_src/handling_errors/tutorial004.py index 8c2c3dec7..0b1c0068a 100644 --- a/docs_src/handling_errors/tutorial004.py +++ b/docs_src/handling_errors/tutorial004.py @@ -1,9 +1,9 @@ from fastapi import FastAPI, HTTPException, Request +from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse -from starlette.exceptions import HTTPException as StarletteHTTPException -from fastapi.encoders import jsonable_encoder from starlette import status +from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() @@ -14,10 +14,8 @@ async def http_exception_handler(request: Request, exc: StarletteHTTPException): Handles all HTTPException (Starlette) errors. Returns a JSON response with status code and detail. """ - return JSONResponse( - status_code=exc.status_code, - content={"message": exc.detail} - ) + return JSONResponse(status_code=exc.status_code, content={"message": exc.detail}) + @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): @@ -27,16 +25,13 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE """ return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, - content=jsonable_encoder({"errors": exc.errors(), "body": exc.body}) + content=jsonable_encoder({"errors": exc.errors(), "body": exc.body}), ) @app.get("/items/{item_id}") async def read_item(item_id: int): - + if item_id == 3: - raise HTTPException( - status_code=418, - detail="Nope! I don't like 3." - ) + raise HTTPException(status_code=418, detail="Nope! I don't like 3.") return {"item_id": item_id}