fastapi 如何在中间件中抛出异样?
chatGPT 给我的计划是:raise HTTPException(status_code=401, detail="Invalid token")
然而理论没用,客户端收到的还是 500
理论应该 return 一个 response
参考代码:
@app.middleware("http")
async def get_user_id(request: Request, call_next):
from core.mysql.models import SessionTable
from core.mysql.models import SessionTable
from core.mysql.models import UserTable
from apps.user.schemas import User
from playhouse.shortcuts import model_to_dict
session_key = request.cookies.get("session_key")
if session_key:
try:
session: SessionTable | None = SessionTable.get_or_none(session_key=session_key)
if session:
user_id = session.user_id
if user_id:
request.state.user_id = user_id
user: UserTable | None = UserTable.get_or_none(id=user_id)
request.state.user = User(**model_to_dict(user))
except Exception as error:
logger.warning(error)
if not session_key or not request.state.get('user_id', None):
return Response(status_code=401, content='Invalid token')
response = call_next(request)
return response