Skip to content

统一异常处理 ​

抛出异常 ​

  • app/applications/errors/exceptions.py
python

from typing import Any

class AppException(RuntimeError):
    """基础应用异常类,继承RuntimeError,用于自定义应用异常"""
    def __init__(self,code:int=400,status_code: int = 400,msg: str = "应用发生错误请稍后尝试",data: Any = None):
        """ 构造函数,初始化异常状态码,消息,数据"""
        self.status_code = status_code
        self.code = code
        self.msg = msg
        self.data = data
        super().__init__()

class BadRequest(AppException):
    """400错误请求异常类,继承AppException,用于自定义错误请求异常"""
    def __init__(self,msg: str = "客户端请求错误请检查后重试"):
        super().__init__(status_code=400,code=400,msg=msg)


class NotFoundError(AppException):
    """ 404错误请求异常类,继承AppException,用于自定义错误请求异常"""
    def __init__(self,msg: str = "资源不存在"):
        super().__init__(status_code=404,code=404,msg=msg)


class ValidationError(AppException):
    """数据校验错误"""
    def __init__(self,msg: str = "请求参数数据校验错误,请核实后重试"):
        super().__init__(status_code=422,code=422,msg=msg)

class TooManyRequestsError(AppException):
    """请求频率过高,触发限流"""
    def __init__(self,msg: str = "请求过多,触发限流,请稍后重试"):
        super().__init__(status_code=429,code=429,msg=msg)

class ServerError(AppException):
    """服务器异常错误"""
    def __init__(self,msg: str = "服务器出现异常,请稍后重试"):
        super().__init__(status_code=500,code=500,msg=msg)

捕获异常 ​

  • interfaces/errors/exception_handlers.py
python
import json
import logging

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException

from app.application.errors.exceptions import AppException
from app.interfaces.schemas import Response

logger = logging.getLogger(__name__)


def register_exception_handlers(app: FastAPI):
    """处理项目中所有的异常并进行统一处理,涵盖 自定义业务异常.HTTP异常,通用异常"""

    # 捕获基类的异常。那里面的都能捕获到。
    @app.exception_handler(AppException)
    async def app_exception_handler(request: Request, e: AppException) -> JSONResponse:
        """处理项目中抛出的APP异常,将状态码统一设置为400"""
        logger.error(f"APPException异常: {e.msg}")
        return JSONResponse(
            status_code=e.status_code,
            content=Response(
                code=e.code,
                msg=e.msg,
                data=e.data or {},
            ).model_dump(),
        )

    # 处理HTTP异常
    @app.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, e: HTTPException) -> JSONResponse:
        """处理项目中抛出的HTTP异常,将状态码统一设置为400"""
        logger.error(f"HTTP异常: {e.detail}")
        return JSONResponse(
            status_code=e.status_code,
            content=Response(
                code=e.status_code,
                msg=e.detail
                if isinstance(e.detail, str)
                else json.dumps(e.detail, ensure_ascii=False),
                data={},
            ).model_dump(),
        )

    # 处理未定义异常
    @app.exception_handler(Exception)
    async def exception_handler(request: Request, e: Exception) -> JSONResponse:
        """处理项目中抛出的未定义的任意异常,将状态码统一设置为500"""
        logger.error(f"未定义异常: {e}")
        return JSONResponse(
            status_code=500,
            content=Response(
                code=500,
                msg="服务器出现异常请稍后重试",
                data={},
            ).model_dump(),
        )

main.py 里面使用异常 ​

python

import logging

from fastapi import FastAPI

from app.infrastructure.loggings.logger import setup_logging
from core.config import get_settings

# 加载生命周期函数
from contextlib import asynccontextmanager

# 加载路由
from app.interfaces.endpoints.routes import router

# 加载中间件
from fastapi.middleware.cors import CORSMiddleware

# 加载异常处理器
from app.interfaces.errors.exception_handlers import register_exception_handlers

# 1.加载配置信息
settings = get_settings()

# 2.初始化日志,业务模块无需重复调用
setup_logging()
logger = logging.getLogger(__name__)

# 3. 定义FastApi路由 Tag标签
openapi_tags = [
  {
    "name":"状态模块",
    "description":"包含**状态监测**等API接口,用于监测系统的运行状态"
  }
]

# 生命周期函数
@asynccontextmanager
async def lifespan(app: FastAPI):
  logger.info("生命周期应用启动")
  try:
    # lifespan 节点/分界
    yield
  finally:
    logger.info("生命周期应用关闭")



# 4.创建应用
app = FastAPI(
  title="我的通用智能体",
  description="一个通用的智能体系统,可以完全私有化部署,使用A2A+MCP连接Agent/Tool,同时支持在沙箱中运行各种内置工具和操作,用于处理各种任务和场景",
  version="1.0.0",
  openapi_tags=openapi_tags,
  lifespan=lifespan,
)

# 5.配置cros中间件。解决跨域问题
app.add_middleware(  # 向 FastAPI 应用注册中间件
  CORSMiddleware,  # 使用 CORS 中间件处理跨域资源共享
  allow_origins=["*"],  # 允许所有来源(协议、域名和端口)发起跨域请求
  allow_credentials=True,  # 允许跨域请求携带 Cookie 等凭据
  allow_methods=["*"],  # 允许所有 HTTP 方法,如 GET、POST、PUT、DELETE
  allow_headers=["*"],  # 允许跨域请求携带所有请求头
)

# 6. 注册错误处理器
register_exception_handlers(app)


# 7.集成路由,固定前缀 /api

app.include_router(router,prefix="/api")

logger.info("应用初始化完成")

测试 ​

bash
http://localhost:8000/67676

这个时候他就应该是 404