fix: unify error response format with error_code, message and domain fields

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Misaka_Company
2026-05-11 12:38:37 +08:00
parent 6a4ea34e24
commit e9bb9d6be0
5 changed files with 72 additions and 27 deletions

View File

@@ -1,26 +1,55 @@
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.api.v1.location import router as location_router
from app.services.location_service import DuplicateLocationError
app = FastAPI(title="CargoTrace API", version="0.1.0")
app.include_router(location_router, prefix="/CargoTrace")
@app.exception_handler(DuplicateLocationError)
async def duplicate_location_handler(request: Request, exc: DuplicateLocationError):
return JSONResponse(
status_code=409,
content={
"error_code": "DUPLICATE_LOCATION",
"message": "该总排号已存在货位记录",
"location_code": exc.location_code,
"registered_at": exc.registered_at,
},
)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
for err in exc.errors():
msg = err.get("msg", "")
if "INVALID_ZONGPAI" in msg or "INVALID_LOCATION" in msg:
error_code = msg.replace("Value error, ", "")
return JSONResponse(
status_code=400,
content={
"error_code": error_code,
"message": error_code,
},
)
return JSONResponse(
status_code=422,
content={"detail": exc.errors()},
)
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
error_code = str(exc)
status_map = {
"INVALID_ZONGPAI": 400,
"INVALID_LOCATION": 400,
}
status = status_map.get(error_code, 400)
return JSONResponse(
status_code=status,
status_code=400,
content={
"error_code": error_code,
"message": str(exc),
"message": error_code,
},
)