unis-oa/backend/app/envelope.py

255 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Response envelope and error handling shared with the sub2api front end.
The front end axios client unwraps ``{"code": 0, "message": "", "data": ...}``
and rejects anything whose ``code`` is not ``0``, so every endpoint speaks it.
"""
from __future__ import annotations
import logging
from typing import Any, Generic, TypeVar
from uuid import uuid4
from fastapi import HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from starlette.exceptions import HTTPException as RawHTTPException
T = TypeVar("T")
#: 给用户看的一句话与写进日志的诊断信息分两路:界面上只留中文,英文原文进日志
logger = logging.getLogger("unisoa.error")
class ApiResponse(BaseModel, Generic[T]):
code: int = 0
message: str = ""
data: T | None = None
def ok(data: Any = None, message: str = "") -> dict[str, Any]:
return {"code": 0, "message": message, "data": data}
class ApiError(HTTPException):
"""Business error carrying a stable ``code`` string for the client."""
def __init__(
self,
message: str,
code: int = status.HTTP_400_BAD_REQUEST,
reason: str = "",
http_status: int | None = None,
data: Any | None = None,
) -> None:
self.reason = reason or f"HTTP_{http_status or code}"
self.api_code = code
#: 少数失败需要带一份结构化附件(强制改密要交回一次性 handle 与生效中的口令规则,
#: 前端拿它重新渲染表单,不必为这一次失败再发一个请求)。默认还是 ``null``。
self.data = data
super().__init__(status_code=http_status or code, detail=message)
def unauthorized(
message: str = "未登录或登录已过期", reason: str = "UNAUTHORIZED", data: Any | None = None
) -> ApiError:
return ApiError(message, 401, reason, http_status=status.HTTP_401_UNAUTHORIZED, data=data)
def forbidden(message: str = "没有权限执行该操作", reason: str = "FORBIDDEN") -> ApiError:
"""403。``reason`` 与 ``unauthorized`` / ``bad_request`` 同一用途:让调用方按码分支,
不必去比对那句给人看的中文(措辞会改,码不会)。"""
return ApiError(message, 403, reason, http_status=status.HTTP_403_FORBIDDEN)
def not_found(message: str = "记录不存在") -> ApiError:
return ApiError(message, 404, "NOT_FOUND", http_status=status.HTTP_404_NOT_FOUND)
def bad_request(
message: str, reason: str = "BAD_REQUEST", data: Any | None = None
) -> ApiError:
return ApiError(message, 400, reason, http_status=status.HTTP_400_BAD_REQUEST, data=data)
#: HTTP 自带的英文状态短语("Method Not Allowed" 那一类)直接甩到界面上没人看得懂,
#: 这里按状态码换成一句人话。业务代码抛的中文错误不经过这张表,原样透出。
_FRAMEWORK_MESSAGES: dict[int, str] = {
400: "请求内容看不明白,请刷新页面后重试",
401: "未登录或登录已过期",
403: "没有权限执行该操作",
# 404 不在这张表里:接口路径与静态资源是两句不同的话,见 framework_message
405: "这个操作当前不支持,请刷新页面后重试",
406: "请求的内容格式不被支持",
408: "请求超时了,请稍后重试",
413: "内容太大传不上去,请精简后再试",
415: "这种格式的内容这里收不了",
422: "参数校验失败",
429: "操作太频繁了,请稍后再试",
500: "服务器内部错误,请稍后重试",
502: "上游服务没有回应,请稍后重试",
503: "服务暂时不可用,请稍后重试",
504: "上游服务响应超时,请稍后重试",
}
#: pydantic 的报错类型 -> 界面上的一句话。宁可说得粗一点,也别糊用户一脸英文,
#: 每条原始报错都会写进日志(见 _validation_handler)。
_VALIDATION_HINTS: dict[str, str] = {
"missing": "是必填的,不能空着",
"extra_forbidden": "是不支持的字段,请刷新页面后重试",
"string_type": "要填文本",
"int_parsing": "要填整数",
"int_type": "要填整数",
"float_parsing": "要填数字",
"float_type": "要填数字",
"bool_parsing": "只能是打开或关闭",
"bool_type": "只能是打开或关闭",
"json_invalid": "不是合法的内容格式",
"json_type": "不是合法的内容格式",
"list_type": "要填一组值",
"set_type": "要填一组值",
"dict_type": "要填一组键值",
"model_attributes_type": "格式不对,应该是一组键值",
"uuid_parsing": "编号格式不对",
"email_parsing": "不是邮箱地址",
"date_parsing": "日期格式不对,形如 2026-09-16",
"datetime_parsing": "时间格式不对,形如 2026-09-16 12:00:00",
"time_parsing": "时间格式不对,形如 12:00:00",
"enum": "不在可选范围里",
"literal_error": "不在可选范围里",
"value_error": "的内容不被接受",
}
#: 字段路径里这些前缀是给路由用的,给用户看只会添乱
_LOC_NOISE = ("body", "query", "path", "header", "cookie")
def _is_chinese(text: str) -> bool:
return any("\u4e00" <= ch <= "\u9fff" for ch in text)
def _known_path(app: Any, path: str) -> bool:
"""这个路径上是不是真挂了一个接口(托管前端的那个兜底路由不算)。"""
for route in getattr(app, "routes", []):
regex = getattr(route, "path_regex", None)
if regex is None or str(getattr(route, "path_format", "")).startswith("/{full_path"):
continue
if regex.match(path):
return True
return False
def framework_message(code: int, detail: object, path: str = "") -> str:
"""框架错误的中文说法:业务代码抛的中文照旧,HTTP 默认的英文换成人话。"""
text = str(detail or "").strip()
if text and _is_chinese(text):
return text
if code == status.HTTP_404_NOT_FOUND:
return "接口不存在" if path.startswith("api/") else "资源不存在"
return _FRAMEWORK_MESSAGES.get(code) or text or f"请求失败({code})"
def _bound_text(etype: str, ctx: dict[str, Any]) -> str:
"""长度与取值范围这类限制 pydantic 只给英文,这里补一句中文。"""
if etype.endswith(("too_short", "too_long")):
low = etype.endswith("too_short")
key = "min" if low else "max"
bound = next((ctx[k] for k in (f"{key}_length", f"{key}_items", f"{key}_digits") if ctx.get(k) is not None), None)
unit = "个字符" if etype.startswith(("string", "bytes")) else "项" if etype.startswith(("list", "set", "tuple")) else "个"
if bound is None:
return "填得太短" if low else "填得太长"
return f"太短了,至少要 {bound} {unit}" if low else f"太长了,最多 {bound} {unit}"
if "greater_than" in etype or "less_than" in etype:
big = "greater_than" in etype
word = "大于" if big else "小于"
if etype.endswith("equal"):
word += "等于"
keys = ("gt", "ge") if big else ("lt", "le")
bound = next((ctx[k] for k in keys if ctx.get(k) is not None), None)
if bound is None:
return "填得太小" if big else "填得太大"
return f"要{word} {bound}"
return ""
def validation_message(errors: list[dict[str, Any]]) -> str:
"""把第一条校验错误说成一句中文,细节全部写进日志。"""
for err in errors:
etype = str(err.get("type") or "")
parts = [str(part) for part in err.get("loc", ())]
field = ".".join(part for part in parts if part not in _LOC_NOISE and not part.isdigit())
ctx = err.get("ctx") or {}
text = _bound_text(etype, ctx) or _VALIDATION_HINTS.get(etype, "")
if not text:
raw = str(err.get("msg") or "")
text = raw if _is_chinese(raw) else "格式不对"
logger.info("参数校验未通过:%s (%s) :: %s", ".".join(parts), etype, err.get("msg"))
return " ".join((f"参数校验失败:{field} {text}" if field else f"参数校验失败:{text}").split())
return "参数校验失败"
def install_exception_handlers(app) -> None:
@app.exception_handler(ApiError)
async def _api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
# 401 在访问日志里只有一句 "401 Unauthorized",这几种情况的查法可完全不同:
# 头没带(浏览器压根没种上会话,或有调用方绕开了 axios 客户端)、令牌到点
# (该走静默续期)、签名认不出(jwt_secret 换过)。这里补一句原因,
# 令牌本身一个字符都不记。
if exc.status_code == status.HTTP_401_UNAUTHORIZED:
logger.info(
"登录态未通过:%s %s reason=%s Authorization=%s",
request.method,
request.url.path,
exc.reason,
"带了" if request.headers.get("authorization") else "没带",
)
return JSONResponse(
status_code=exc.status_code,
content={"code": exc.api_code, "message": exc.detail, "reason": exc.reason,
"data": exc.data},
)
# 挂 Starlette 的 HTTPException 而不是 FastAPI 那个子类:405 这类框架自己抛的错是父类
# 实例,只挂子类会整个漏掉,界面上就只剩 "Request failed with status code 405"。
@app.exception_handler(RawHTTPException)
async def _http_error_handler(request: Request, exc: RawHTTPException) -> JSONResponse:
path = request.url.path.lstrip("/")
code = exc.status_code
# 托管前端的兜底路由把每个路径都兜成"路径在、只是方法不对",于是压根没这个接口
# 时也回 405;路径上确实没挂接口就说实话,别让人以为换个方法就能通。
if code == status.HTTP_405_METHOD_NOT_ALLOWED and not _known_path(request.app, request.url.path):
code = status.HTTP_404_NOT_FOUND
return JSONResponse(
status_code=code,
content={"code": code, "message": framework_message(code, exc.detail, path), "data": None},
)
@app.exception_handler(RequestValidationError)
async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={
"code": 400,
"message": validation_message(list(exc.errors())),
"reason": "VALIDATION_ERROR",
"data": None,
},
)
# 异常原文里可能带 SQL、机器路径、内网地址,一个字都不进响应体;
# 给用户一个能报给管理员的编号,日志里按编号找完整堆栈。
@app.exception_handler(Exception)
async def _unhandled_handler(request: Request, exc: Exception) -> JSONResponse: # pragma: no cover
ref = uuid4().hex[:8]
logger.exception("未处理异常 %s(编号 %s)", request.url.path, ref)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"code": 500,
"message": f"{_FRAMEWORK_MESSAGES[500]}(编号 {ref})",
"reason": "INTERNAL_ERROR",
"data": None,
},
)