exceptions.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from fastapi import FastAPI, Request
  2. from fastapi.responses import JSONResponse
  3. class DocumentNotFoundError(Exception):
  4. def __init__(self, document_id: str):
  5. self.document_id = document_id
  6. super().__init__(f"Document '{document_id}' not found")
  7. class ContentTooLargeError(Exception):
  8. def __init__(self, size: int, limit: int = 200_000):
  9. super().__init__(f"Content size {size} bytes exceeds limit of {limit} bytes")
  10. class ExportError(Exception):
  11. def __init__(self, reason: str):
  12. super().__init__(f"Export failed: {reason}")
  13. def register_exception_handlers(app: FastAPI) -> None:
  14. @app.exception_handler(DocumentNotFoundError)
  15. async def document_not_found_handler(
  16. request: Request, exc: DocumentNotFoundError
  17. ) -> JSONResponse:
  18. return JSONResponse(
  19. status_code=404,
  20. content={"code": 404, "message": str(exc), "data": None},
  21. )
  22. @app.exception_handler(ContentTooLargeError)
  23. async def content_too_large_handler(
  24. request: Request, exc: ContentTooLargeError
  25. ) -> JSONResponse:
  26. return JSONResponse(
  27. status_code=413,
  28. content={"code": 413, "message": str(exc), "data": None},
  29. )
  30. @app.exception_handler(ExportError)
  31. async def export_error_handler(
  32. request: Request, exc: ExportError
  33. ) -> JSONResponse:
  34. return JSONResponse(
  35. status_code=500,
  36. content={"code": 500, "message": str(exc), "data": None},
  37. )