| 1 |
from fastapi import FastAPI, HTTPException |
| 2 |
from fastapi.exceptions import RequestValidationError |
| 3 |
from fastapi.responses import PlainTextResponse |
| 4 |
from starlette.exceptions import HTTPException as StarletteHTTPException |
| 5 |
|
| 6 |
app = FastAPI() |
| 7 |
|
| 8 |
|
| 9 |
@app.exception_handler(StarletteHTTPException) |
| 10 |
async def http_exception_handler(request, exc): |
| 11 |
return PlainTextResponse(str(exc.detail), status_code=exc.status_code) |
| 12 |
|
| 13 |
|
| 14 |
@app.exception_handler(RequestValidationError) |
| 15 |
async def validation_exception_handler(request, exc: RequestValidationError): |
| 16 |
message = "Validation errors:" |
| 17 |
for error in exc.errors(): |
| 18 |
message += f"\nField: {error['loc']}, Error: {error['msg']}" |
| 19 |
return PlainTextResponse(message, status_code=400) |
| 20 |
|
| 21 |
|
| 22 |
@app.get("/items/{item_id}") |
| 23 |
async def read_item(item_id: int): |
| 24 |
if item_id == 3: |
| 25 |
raise HTTPException(status_code=418, detail="Nope! I don't like 3.") |
| 26 |
return {"item_id": item_id} |