在 FastAPI 應用程式中,處理錯誤對於向客戶端提供資訊豐富的回應至關重要。遇到的常見問題是在請求中發送附加資料或無效資料時收到 422 Unprocessable Entity 錯誤。本文將示範如何自訂錯誤回應來處理此類情況。
考慮以下FastAPI 後端範例:
from fastapi import FastAPI app = FastAPI class Demo(BaseModel): content: str = None @app.post("/demo") async def demoFunc(d: Demo): return d.content
傳送帶有額外資料的請求時,例如data = { "content": "some text here"}aaaa,API 傳回422錯誤,回應如下:
{ "detail": [ { "loc": [ "body", 47 ], "msg": "Extra data: line 4 column 2 (char 47)", "type": "value_error.jsondecode", "ctx": { "msg": "Extra data", "doc": "{\n \"content\": \"some text here\"}aaaaa", "pos": 47, "lineno": 4, "colno": 2 } } ] }
要自訂錯誤回應,FastAPI 允許覆寫請求驗證異常處理程序。首先匯入必要的模組並定義自訂異常處理函數:
from fastapi import FastAPI, Body, Request, status from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({ "detail": exc.errors(), "body": exc.body, "custom msg": { "Your error message" } }), )
此函數攔截 RequestValidationError 異常並產生自訂的 JSON 回應。您可以包含錯誤詳細資訊、請求正文和任何自訂訊息。
例如,使用無效的JSON 正文現在將導致類似於以下內容的回應:
{ "detail": [ { "loc": ["body", 1], "msg": "invalid json", "type": "json.decoder.JSONDecodeError", "ctx": {} } ], "body": {}, "custom msg": { "Your error message" } }
或者,您可以傳回僅包含錯誤訊息的純文字回應:
from fastapi.responses import PlainTextResponse @app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc): return PlainTextResponse(str(exc), status_code=422)
透過自訂FastAPI 中的錯誤回應行為,您可以為API 提供更多資訊且一致的錯誤處理。這改善了用戶體驗並簡化了開發人員和 API 用戶的偵錯。
以上是如何在 FastAPI 中自訂無效請求的錯誤回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!