コンテンツへスキップ

例外 - HTTPException および WebSocketException

これらは、クライアントにエラーを表示するために発生させることができる例外です。

例外を発生させると、通常の 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 ''