LoginSignup
0
3

More than 3 years have passed since last update.

FastAPIについて ~エンドポイントエラーハンドリング~

Last updated at Posted at 2020-09-07

FastAPIエラーハンドリングサンプル

FastAPI version_0.61.1
Documentation: https://fastapi.tiangolo.com
Source Code: https://github.com/tiangolo/fastapi

FastAPIのエンドポイントは下記のように実装することで
エラーハンドリング可能になる。

sample.py
from fastapi import routing
def handle_wrapper(func):
    def routing_wrapper(*args, **kwargs):
        routing_api = func(*args, **kwargs)
        async def api_handle(request: Request) -> Response:
            try:
                http_response = await routing_api(request)
            except Exception as ex:
                """ここに任意の例外処理を記述する"""
            return http_response
        return api_handle
    return routing_wrapper
routing.get_request_handler = handle_wrapper(routing.get_request_handler)
http_response = await routing_api(request)

このコードの7行目↑にてエンドポイントが呼び出されるため、
上記コードを応用してコールバック関数を定義することも可能となる。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3