Files
doluedu-fastapi-template/src/exceptions.py
ghplvh 981bee5a46 feat: 改造为开箱即用模板 — MySQL/MongoDB(Beanie) 一键切换 + AGENTS.md 开发规范
- src/ 按域组织骨架,示例域 items 双后端实现(SQLAlchemy2.0 async / Beanie 2.x)
- DB_BACKEND 环境变量切换,router 只依赖 Repo Protocol
- alembic 迁移(含初始 items 迁移)、uv 依赖管理、ruff、pytest 异步测试
- Dockerfile + docker-compose(app/mysql/mongo)
- AGENTS.md 重写为本模板开发规范;原最佳实践文档归档 docs/
- 验证:mongodb/mysql 双后端 pytest 全绿 + uvicorn 真实冒烟通过
2026-08-21 21:23:26 +08:00

27 lines
814 B
Python

"""全局异常 + 统一错误响应。"""
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
class AppError(Exception):
"""业务异常基类。子类在各域 exceptions.py 中定义。"""
status_code: int = status.HTTP_400_BAD_REQUEST
detail: str = "bad request"
def __init__(self, detail: str | None = None):
self.detail = detail or self.detail
super().__init__(self.detail)
class NotFoundError(AppError):
status_code = status.HTTP_404_NOT_FOUND
detail = "not found"
def register_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def app_error_handler(_: Request, exc: AppError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})