FastAPI 错误处理与自定义错误消息完全指南:构建健壮的 API 应用 🛠️
title: FastAPI 错误处理与自定义错误消息完全指南:构建健壮的 API 应用 🛠️
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id != 1:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
from fastapi import Request, FastAPI, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail, "error": "Custom error message"},
)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id != 1:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
curl "http://localhost:8000/items/2"
{
"detail": "Item not found",
"error": "Custom error message"
}
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"detail": "An unexpected error occurred", "error": str(exc)},
)
import logging
logging.basicConfig(level=logging.INFO)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
logging.error(f"Unexpected error: {exc}")
return JSONResponse(
status_code=500,
content={"detail": "An unexpected error occurred"},
)
评论
发表评论