exceptions.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from fastapi import FastAPI, Request
  2. from fastapi.responses import JSONResponse
  3. class DocumentNotFoundError(Exception):
  4. def __init__(self, document_id: str):
  5. super().__init__(f"Document '{document_id}' not found")
  6. class DocumentParseError(Exception):
  7. """Word 下载或解析失败。"""
  8. pass
  9. class ExportError(Exception):
  10. pass
  11. class RecordNotFoundError(Exception):
  12. def __init__(self, record_id: str):
  13. super().__init__(f"Export record '{record_id}' not found")
  14. # 异常映射配置:异常类 -> (HTTP状态码, 业务错误码)
  15. EXCEPTION_MAPPINGS: dict[type[Exception], tuple[int, int]] = {
  16. DocumentNotFoundError: (404, 404),
  17. DocumentParseError: (400, 400),
  18. ExportError: (500, 500),
  19. RecordNotFoundError: (404, 4041),
  20. }
  21. def register_exception_handlers(app: FastAPI) -> None:
  22. """注册全局异常处理器,所有自定义异常返回标准格式:{"code": int, "message": str, "data": None}"""
  23. async def unified_exception_handler(request: Request, exc: Exception) -> JSONResponse:
  24. """统一异常处理函数"""
  25. # 从映射中获取配置,如果不存在则使用默认值 (500, 500)
  26. http_status, error_code = EXCEPTION_MAPPINGS.get(type(exc), (500, 500))
  27. return JSONResponse(
  28. status_code=http_status,
  29. content={
  30. "code": error_code,
  31. "message": str(exc),
  32. "data": None,
  33. },
  34. )
  35. # 为所有配置的异常类型注册同一个处理函数
  36. for exc_class in EXCEPTION_MAPPINGS:
  37. app.add_exception_handler(exc_class, unified_exception_handler)