exceptions.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. _HANDLERS: list[tuple[type[Exception], int, int]] = [
  15. (DocumentNotFoundError, 404, 404),
  16. (DocumentParseError, 400, 400),
  17. (ExportError, 500, 500),
  18. (RecordNotFoundError, 404, 4041),
  19. ]
  20. def register_exception_handlers(app: FastAPI) -> None:
  21. def _make_handler(http_status: int, code: int):
  22. async def handler(request: Request, exc: Exception) -> JSONResponse:
  23. return JSONResponse(
  24. status_code=http_status,
  25. content={"code": code, "message": str(exc), "data": None},
  26. )
  27. return handler
  28. for exc_class, http_status, code in _HANDLERS:
  29. app.add_exception_handler(exc_class, _make_handler(http_status, code))