166 lines
5.3 KiB
Python
166 lines
5.3 KiB
Python
"""统一响应包装与错误模型。
|
||
|
||
前端只需要认一种形状:``{"ok": true, "data": ...}`` / ``{"ok": false, "error": {...}}``。
|
||
错误对象里固定带 ``code``(机器读)、``message``(人读)、``detail``(表单级字段错误)
|
||
和 ``traceId``(排障用),因此 422 校验、业务异常、未捕获异常在前端走同一段代码。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import uuid
|
||
from typing import Any, Generic, TypeVar
|
||
|
||
from fastapi import FastAPI, Request, status
|
||
from fastapi.exceptions import RequestValidationError
|
||
from fastapi.responses import JSONResponse
|
||
from pydantic import BaseModel, Field
|
||
|
||
logger = logging.getLogger("pms.api")
|
||
|
||
T = TypeVar("T")
|
||
|
||
|
||
class ErrorBody(BaseModel):
|
||
code: str
|
||
message: str
|
||
detail: Any | None = None
|
||
|
||
|
||
class ApiResponse(BaseModel, Generic[T]):
|
||
ok: bool = True
|
||
data: T | None = None
|
||
error: ErrorBody | None = None
|
||
|
||
|
||
class PageMeta(BaseModel):
|
||
total: int = 0
|
||
page: int = 1
|
||
page_size: int = Field(default=20, alias="pageSize")
|
||
|
||
model_config = {"populate_by_name": True}
|
||
|
||
|
||
class PageData(BaseModel, Generic[T]):
|
||
items: list[T] = Field(default_factory=list)
|
||
meta: PageMeta
|
||
|
||
|
||
def ok(data: Any = None) -> dict[str, Any]:
|
||
return {"ok": True, "data": data}
|
||
|
||
|
||
def page(items: list[Any], total: int, page_no: int, page_size: int) -> dict[str, Any]:
|
||
return {
|
||
"ok": True,
|
||
"data": {
|
||
"items": items,
|
||
"meta": {"total": total, "page": page_no, "pageSize": page_size},
|
||
},
|
||
}
|
||
|
||
|
||
class ApiError(Exception):
|
||
"""业务异常。抛这个,中间件会翻成人话并带上 traceId。"""
|
||
|
||
def __init__(
|
||
self,
|
||
code: str,
|
||
message: str,
|
||
*,
|
||
http_status: int = status.HTTP_400_BAD_REQUEST,
|
||
detail: Any = None,
|
||
) -> None:
|
||
super().__init__(message)
|
||
self.code = code
|
||
self.message = message
|
||
self.http_status = http_status
|
||
self.detail = detail
|
||
|
||
|
||
def not_found(message: str = "记录不存在") -> ApiError:
|
||
return ApiError("not_found", message, http_status=status.HTTP_404_NOT_FOUND)
|
||
|
||
|
||
def forbidden(message: str = "没有权限执行该操作") -> ApiError:
|
||
return ApiError("forbidden", message, http_status=status.HTTP_403_FORBIDDEN)
|
||
|
||
|
||
def unauthorized(message: str = "登录状态已失效,请重新登录") -> ApiError:
|
||
return ApiError("unauthorized", message, http_status=status.HTTP_401_UNAUTHORIZED)
|
||
|
||
|
||
def bad_request(code: str, message: str, detail: Any = None) -> ApiError:
|
||
"""请求本身没问题,但业务规则不让做:用 400,别和 409 的状态冲突混用。"""
|
||
return ApiError(code, message, http_status=status.HTTP_400_BAD_REQUEST, detail=detail)
|
||
|
||
|
||
def conflict(code: str, message: str, detail: Any = None) -> ApiError:
|
||
return ApiError(code, message, http_status=status.HTTP_409_CONFLICT, detail=detail)
|
||
|
||
|
||
def trace_id(request: Request) -> str:
|
||
return getattr(request.state, "trace_id", "")
|
||
|
||
|
||
def install_handlers(app: FastAPI) -> None:
|
||
"""挂上异常处理与 traceId。"""
|
||
|
||
@app.middleware("http")
|
||
async def attach_trace(request: Request, call_next): # pragma: no cover - 由框架调用
|
||
request.state.trace_id = request.headers.get("X-Trace-Id") or uuid.uuid4().hex[:16]
|
||
response = await call_next(request)
|
||
response.headers["X-Trace-Id"] = request.state.trace_id
|
||
return response
|
||
|
||
@app.exception_handler(ApiError)
|
||
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
|
||
return JSONResponse(
|
||
status_code=exc.http_status,
|
||
content={
|
||
"ok": False,
|
||
"error": {
|
||
"code": exc.code,
|
||
"message": exc.message,
|
||
"detail": exc.detail,
|
||
"traceId": trace_id(request),
|
||
},
|
||
},
|
||
)
|
||
|
||
@app.exception_handler(RequestValidationError)
|
||
async def handle_validation(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||
fields: dict[str, str] = {}
|
||
for item in exc.errors():
|
||
location = ".".join(str(part) for part in item.get("loc", ()) if part != "body")
|
||
fields[location or "body"] = item.get("msg", "格式不正确")
|
||
return JSONResponse(
|
||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||
content={
|
||
"ok": False,
|
||
"error": {
|
||
"code": "validation_failed",
|
||
"message": "提交的表单有 "
|
||
f"{len(fields)} 处不符合要求",
|
||
"detail": {"fields": fields},
|
||
"traceId": trace_id(request),
|
||
},
|
||
},
|
||
)
|
||
|
||
@app.exception_handler(Exception)
|
||
async def handle_unexpected(request: Request, exc: Exception) -> JSONResponse: # pragma: no cover
|
||
logger.exception("未处理异常 traceId=%s path=%s", trace_id(request), request.url.path)
|
||
return JSONResponse(
|
||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||
content={
|
||
"ok": False,
|
||
"error": {
|
||
"code": "internal_error",
|
||
"message": "服务器内部错误,请把 traceId 发给管理员",
|
||
"detail": None,
|
||
"traceId": trace_id(request),
|
||
},
|
||
},
|
||
)
|