跳至內容

例外 - HTTPExceptionWebSocketException

這些是您可以引發以向用戶端顯示錯誤的例外。

當您引發例外時,就像一般的 Python 行為一樣,其餘的執行會被中止。透過這種方式,您可以從程式碼中的任何位置引發這些例外,以中止請求並向用戶端顯示錯誤。

您可以使用

  • HTTPException
  • WebSocketException

這些例外可以直接從 fastapi 匯入

from fastapi import HTTPException, WebSocketException

fastapi.HTTPException

HTTPException(status_code, detail=None, headers=None)

基底: HTTPException

您可以在自己的程式碼中引發的 HTTP 例外,以向用戶端顯示錯誤。

這是針對用戶端錯誤、無效的驗證、無效的資料等。而不是針對您程式碼中的伺服器錯誤。

FastAPI 處理錯誤的說明文件中了解更多資訊。

範例

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}


@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}
參數 說明
status_code

要傳送給用戶端的 HTTP 狀態碼。

類型: int

detail

要在 JSON 回應的 detail 鍵中傳送給用戶端的任何資料。

類型: Any 預設值: None

headers

要在回應中傳送給用戶端的任何標頭。

類型: Optional[Dict[str, str]] 預設值: None

原始程式碼位於 fastapi/exceptions.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def __init__(
    self,
    status_code: Annotated[
        int,
        Doc(
            """
            HTTP status code to send to the client.
            """
        ),
    ],
    detail: Annotated[
        Any,
        Doc(
            """
            Any data to be sent to the client in the `detail` key of the JSON
            response.
            """
        ),
    ] = None,
    headers: Annotated[
        Optional[Dict[str, str]],
        Doc(
            """
            Any headers to send to the client in the response.
            """
        ),
    ] = None,
) -> None:
    super().__init__(status_code=status_code, detail=detail, headers=headers)

status_code 實例屬性

status_code = status_code

detail 實例屬性

detail = detail

headers 實例屬性

headers = headers

fastapi.WebSocketException

WebSocketException(code, reason=None)

基底: WebSocketException

您可以在自己的程式碼中引發的 WebSocket 例外,以向用戶端顯示錯誤。

這是針對用戶端錯誤、無效的驗證、無效的資料等。而不是針對您程式碼中的伺服器錯誤。

FastAPI WebSockets 的說明文件中了解更多資訊。

範例

from typing import Annotated

from fastapi import (
    Cookie,
    FastAPI,
    WebSocket,
    WebSocketException,
    status,
)

app = FastAPI()

@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
    *,
    websocket: WebSocket,
    session: Annotated[str | None, Cookie()] = None,
    item_id: str,
):
    if session is None:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Session cookie is: {session}")
        await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
參數 說明
code

來自 規範中定義的有效程式碼 的關閉程式碼。

類型: int

reason

關閉 WebSocket 連線的原因。

此資料採用 UTF-8 編碼。原因的詮釋由應用程式自行決定,WebSocket 規範並未明確定義。

它可以包含人類可讀或客戶端程式碼可解釋的文字等。

類型: Union[str, None] 預設值: None

原始程式碼位於 fastapi/exceptions.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def __init__(
    self,
    code: Annotated[
        int,
        Doc(
            """
            A closing code from the
            [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
            """
        ),
    ],
    reason: Annotated[
        Union[str, None],
        Doc(
            """
            The reason to close the WebSocket connection.

            It is UTF-8-encoded data. The interpretation of the reason is up to the
            application, it is not specified by the WebSocket specification.

            It could contain text that could be human-readable or interpretable
            by the client code, etc.
            """
        ),
    ] = None,
) -> None:
    super().__init__(code=code, reason=reason)

code 實體屬性

code = code

reason 實體屬性

reason = reason or ''