mirror of
https://github.com/fastapi/fastapi.git
synced 2026-02-15 08:41:07 -05:00
📝 Update source examples and docs from Python 3.9 to 3.10 (#14900)
This commit is contained in:
committed by
GitHub
parent
d06ab3f5c7
commit
c9e2277d8b
26
docs_src/handling_errors/tutorial004_py310.py
Normal file
26
docs_src/handling_errors/tutorial004_py310.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request, exc):
|
||||
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request, exc: RequestValidationError):
|
||||
message = "Validation errors:"
|
||||
for error in exc.errors():
|
||||
message += f"\nField: {error['loc']}, Error: {error['msg']}"
|
||||
return PlainTextResponse(message, status_code=400)
|
||||
|
||||
|
||||
@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.")
|
||||
return {"item_id": item_id}
|
||||
Reference in New Issue
Block a user