From 1f0c5769ce05dcced56bfa4d4309c1888824f501 Mon Sep 17 00:00:00 2001 From: Shaptain Date: Thu, 4 Sep 2025 17:34:52 +0530 Subject: [PATCH] docs: improve tutorial002.py with clearer comments and docstrings, improve tutorial004.py withdocstrings for the route and exception handler --- docs_src/handling_errors/tutorial002.py | 1 + docs_src/handling_errors/tutorial004.py | 35 +++++++++++++++++++------ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/docs_src/handling_errors/tutorial002.py b/docs_src/handling_errors/tutorial002.py index e48c295c9..e4d388e24 100644 --- a/docs_src/handling_errors/tutorial002.py +++ b/docs_src/handling_errors/tutorial002.py @@ -7,6 +7,7 @@ items = {"foo": "The Foo Wrestlers"} @app.get("/items-header/{item_id}") async def read_item_header(item_id: str): + if item_id not in items: raise HTTPException( status_code=404, diff --git a/docs_src/handling_errors/tutorial004.py b/docs_src/handling_errors/tutorial004.py index 300a3834f..8c2c3dec7 100644 --- a/docs_src/handling_errors/tutorial004.py +++ b/docs_src/handling_errors/tutorial004.py @@ -1,23 +1,42 @@ -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Request from fastapi.exceptions import RequestValidationError -from fastapi.responses import PlainTextResponse +from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException +from fastapi.encoders import jsonable_encoder +from starlette import status app = FastAPI() @app.exception_handler(StarletteHTTPException) -async def http_exception_handler(request, exc): - return PlainTextResponse(str(exc.detail), status_code=exc.status_code) - +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} + ) @app.exception_handler(RequestValidationError) -async def validation_exception_handler(request, exc): - return PlainTextResponse(str(exc), status_code=400) +async def validation_exception_handler(request: Request, exc: RequestValidationError): + """ + Handles validation errors for request data. + Returns a JSON response with 400 status and error details. + """ + return JSONResponse( + status_code=status.HTTP_400_BAD_REQUEST, + 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}