fastapi中间件异常处理

1.在fastapi的中间件中,如果不做处理直接抛出HttpException,框架是不会捕获并处理成响应的,这时客户端看到的就是500 Internal Server Error。

2.为了能在中间件中直接抛出异常,方便写代码,需要自己添加一个中间件来对所有中间件的异常做处理。
该中间件代码如下:

from typing import Callable

from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse, Response

async def mid_exception_handler(req: Request, call_next: Callable) -> Response:
   """
  中间件异常处理
  需确保这个中间件在最外层
  """
   try:
       resp = await call_next(req)
       return resp
   except HTTPException as http_e:
       # 捕获中间件中的http异常
       return JSONResponse(
           content={"detail": http_e.detail}, status_code=http_e.status_code
      )
   except Exception as e:
       # 未处理错误则判定服务错误
       return JSONResponse(
           status_code=500, content={"message": f"Internal Server Error: {str(e)}"}
      )
 既然这个中间件需要处理所有中间件的异常,那么这个中间件需要在最外层,也就是最后注册。
posted @ 2025-03-07 09:50  CJTARRR  阅读(154)  评论(0)    收藏  举报