Browse Source

docs: improve tutorial002.py with clearer comments and docstrings, improve tutorial004.py withdocstrings for the route and exception handler

pull/14040/head
Shaptain 11 months ago
parent
commit
1f0c5769ce
  1. 1
      docs_src/handling_errors/tutorial002.py
  2. 35
      docs_src/handling_errors/tutorial004.py

1
docs_src/handling_errors/tutorial002.py

@ -7,6 +7,7 @@ items = {"foo": "The Foo Wrestlers"}
@app.get("/items-header/{item_id}") @app.get("/items-header/{item_id}")
async def read_item_header(item_id: str): async def read_item_header(item_id: str):
if item_id not in items: if item_id not in items:
raise HTTPException( raise HTTPException(
status_code=404, status_code=404,

35
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.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.encoders import jsonable_encoder
from starlette import status
app = FastAPI() app = FastAPI()
@app.exception_handler(StarletteHTTPException) @app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc): async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code) """
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) @app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc): async def validation_exception_handler(request: Request, exc: RequestValidationError):
return PlainTextResponse(str(exc), status_code=400) """
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}") @app.get("/items/{item_id}")
async def read_item(item_id: int): async def read_item(item_id: int):
if item_id == 3: 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} return {"item_id": item_id}

Loading…
Cancel
Save