如何在 FastAPI 中自訂無效請求的錯誤回應?

Susan Sarandon
發布: 2024-10-21 06:25:03
原創
610 人瀏覽過

How to Customize Error Responses for Invalid Requests in FastAPI?

FastAPI 中的自訂錯誤回應處理

在 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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!