exception.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import textwrap
  2. from typing import Any, Optional
  3. from uuid import UUID
  4. class R2RException(Exception):
  5. def __init__(
  6. self, message: str, status_code: int, detail: Optional[Any] = None
  7. ):
  8. self.message = message
  9. self.status_code = status_code
  10. super().__init__(self.message)
  11. def to_dict(self):
  12. return {
  13. "message": self.message,
  14. "status_code": self.status_code,
  15. "detail": self.detail,
  16. "error_type": self.__class__.__name__,
  17. }
  18. class R2RDocumentProcessingError(R2RException):
  19. def __init__(
  20. self, error_message: str, document_id: UUID, status_code: int = 500
  21. ):
  22. detail = {
  23. "document_id": str(document_id),
  24. "error_type": "document_processing_error",
  25. }
  26. super().__init__(error_message, status_code, detail)
  27. def to_dict(self):
  28. result = super().to_dict()
  29. result["document_id"] = self.document_id
  30. return result
  31. class PDFParsingError(R2RException):
  32. """Custom exception for PDF parsing errors"""
  33. def __init__(
  34. self,
  35. message: str,
  36. original_error: Exception | None = None,
  37. status_code: int = 500,
  38. ):
  39. detail = {
  40. "original_error": str(original_error) if original_error else None
  41. }
  42. super().__init__(message, status_code, detail)
  43. class PopperNotFoundError(PDFParsingError):
  44. """Specific error for when Poppler is not installed."""
  45. def __init__(self):
  46. installation_instructions = textwrap.dedent(
  47. """
  48. PDF processing requires Poppler to be installed. Please install Poppler and ensure it's in your system PATH.
  49. Installing poppler:
  50. - Ubuntu: sudo apt-get install poppler-utils
  51. - Archlinux: sudo pacman -S poppler
  52. - MacOS: brew install poppler
  53. - Windows:
  54. 1. Download poppler from @oschwartz10612
  55. 2. Move extracted directory to desired location
  56. 3. Add bin/ directory to PATH
  57. 4. Test by running 'pdftoppm -h' in terminal
  58. """
  59. )
  60. super().__init__(
  61. message=installation_instructions,
  62. status_code=422,
  63. original_error=None,
  64. )