# -*- coding: utf-8 -*- """统一应用异常与错误响应。 FastAPI 依赖里无法直接「返回响应短路」,因此用抛出 AppError + 全局异常处理器 的方式,产出与 Flask 侧同形的 JSON 包体({status, success, message, error_code})。 """ from typing import Any from fastapi import Request from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException from web.response import error class AppError(Exception): """业务异常:携带 HTTP 状态码与可选 error_code。""" def __init__(self, message: str, status_code: int = 400, error_code: str | None = None): super().__init__(message) self.message = message self.status_code = status_code self.error_code = error_code def install_error_handlers(app) -> None: @app.exception_handler(AppError) async def _app_error(_request: Request, exc: AppError): return error(exc.message, exc.status_code, exc.error_code) @app.exception_handler(StarletteHTTPException) async def _http_error(_request: Request, exc: StarletteHTTPException) -> Any: # 404/405 等也统一为本站包体(Flask 侧 404 返回 {'success': False, ...}) msg = {404: '请求的资源不存在', 405: '请求方法不允许'}.get(exc.status_code, str(exc.detail or '请求错误')) return error(msg, exc.status_code) @app.exception_handler(RequestValidationError) async def _validation_error(_request: Request, exc: RequestValidationError): return error('请求参数错误', 400)