什麼是自訂例外處理器?
@app.exception_handler() 是 FastAPI 提供的全域例外攔截機制,讓你針對特定類型的例外統一決定回應格式。這比在每個路由中個別撰寫 try/except 更有效率:只需定義一次,全專案所有路由都自動套用。
自訂例外處理器基礎語法
- 定義自訂例外類別,繼承自 Python 內建的 Exception,可加入自訂屬性(例如 code、message)。
- 使用
@app.exception_handler(例外類別) 裝飾處理函式,函式簽名固定為 (request: Request, exc: 例外類別)。 - 處理函式必須回傳 JSONResponse 物件,需從
fastapi.responses匯入,並設定正確的 status_code。 - 攔截 FastAPI 內建的
RequestValidationError可覆寫預設的 422 驗證錯誤格式;攔截 HTTPException 可統一所有 HTTP 錯誤的回應結構。
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
app = FastAPI()
# 1. 定義自訂例外
class BusinessError(Exception):
def __init__(self, code: str, message: str):
self.code = code
self.message = message
# 2. 攔截自訂例外,統一格式回應
@app.exception_handler(BusinessError)
async def business_error_handler(request: Request, exc: BusinessError):
return JSONResponse(
status_code=400,
content={"error_code": exc.code, "message": exc.message},
)
# 3. 覆寫預設 422 驗證錯誤的格式
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={"message": "輸入資料格式錯誤", "detail": exc.errors()},
)
@app.get("/orders/{order_id}")
def get_order(order_id: int):
if order_id == 0:
raise BusinessError(code="INVALID_ID", message="訂單 ID 不可為 0")
return {"order_id": order_id}

















