Files
fastAPI/app/main.py
2026-05-11 12:38:37 +08:00

60 lines
1.8 KiB
Python

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)
return JSONResponse(
status_code=400,
content={
"error_code": error_code,
"message": error_code,
},
)
@app.get("/")
async def root():
return {"message": "Welcome to CargoTrace API"}