[backend] fix: 修复认证相关的测试
- 修改LoginRequest schema,使字段为可选 - 添加自定义异常处理器以返回正确的JSON格式 - 修改认证中间件,返回正确的错误码和响应格式 - 所有auth测试(10个)全部通过 测试结果:10 passed
This commit is contained in:
+35
-1
@@ -1,5 +1,8 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import HTTPException, RequestValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from config.settings import get_settings
|
||||
from config.database import init_db
|
||||
from src.routes import auth_router, users_router, projects_router
|
||||
@@ -27,6 +30,37 @@ app.include_router(users_router, prefix="/api/v1")
|
||||
app.include_router(projects_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
if isinstance(exc.detail, dict):
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=exc.detail,
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"success": False,
|
||||
"message": exc.detail,
|
||||
"data": None,
|
||||
"error_code": None,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"success": False,
|
||||
"message": "请求验证失败",
|
||||
"data": exc.errors(),
|
||||
"error_code": "1001",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
await init_db()
|
||||
|
||||
Reference in New Issue
Block a user