"""统一的 API 业务异常。 前端需要区分「手机号未绑定」「设备不一致」「验证码锁定」等场景, FastAPI 默认的 ``{"detail": "..."}`` 无法携带机器可读的错误码,这里补一个 ``errorCode`` 字段;HTTP 状态码仍是标准语义(401/403/409/426/429)。 """ from __future__ import annotations from fastapi import Request from fastapi.responses import JSONResponse class ApiError(Exception): def __init__(self, status_code: int, detail: str, error_code: str): super().__init__(detail) self.status_code = status_code self.detail = detail self.error_code = error_code async def api_error_handler(_: Request, exc: ApiError) -> JSONResponse: return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail, "errorCode": exc.error_code}, )