LoginSignup
0
0

More than 1 year has passed since last update.

FastAPIのミドルウェアを使ってサーバー全体でエラー処理を行う

Posted at

TL;DR

  • FastAPIのミドルウェアを使えばInternal Server Errorの時にエラー処理を行うことができる
  • ミドルウェアを使うことで、エラー処理を一ヶ所に共通化することができる

背景

FastAPIはルーティング=関数なので、処理のエラー時にはそれぞれの関数でエラー処理を行う必要がある。

@app.get("/route_1")
def routing():
    try:
        # 何かの処理
    except Exception as e:
        # エラー処理

@app.get("/route_2")
def routing():
    try:
        # 何かの処理
    except Exception as e:
        # エラー処理

これは非常に手間だし可読性も悪い。

ミドルウェアを使ってグローバルなエラー処理を行う

まず、ミドルウェアを作成する

@app.middleware("http")
async def exception_handling_middleware(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception as e:
        # エラー処理を行う、例えばSlackに通知する
        slack_notify(e)
        return Response("Internal server error", status_code=500)

これで、全てのルーティングでエラーが発生した時にSlackに通知することができる。
slack_notifyの部分でエラー処理を行っている。
ここを変えれば、例えばDBにエラーを保存したり特殊なレスポンスを返したりすることができる。

まとめ

ミドルウェアを活用しよう。

参考

0
0
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
0