exceptions.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. class RecordNotFoundError(Exception):
  14. def __init__(self, record_id: str):
  15. self.record_id = record_id
  16. super().__init__(f"Export record '{record_id}' not found")
  17. def register_exception_handlers(app: FastAPI) -> None:
  18. @app.exception_handler(DocumentNotFoundError)
  19. async def document_not_found_handler(
  20. request: Request, exc: DocumentNotFoundError
  21. ) -> JSONResponse:
  22. return JSONResponse(
  23. status_code=404,
  24. content={"code": 404, "message": str(exc), "data": None},
  25. )
  26. @app.exception_handler(ContentTooLargeError)
  27. async def content_too_large_handler(
  28. request: Request, exc: ContentTooLargeError
  29. ) -> JSONResponse:
  30. return JSONResponse(
  31. status_code=413,
  32. content={"code": 413, "message": str(exc), "data": None},
  33. )
  34. @app.exception_handler(ExportError)
  35. async def export_error_handler(
  36. request: Request, exc: ExportError
  37. ) -> JSONResponse:
  38. return JSONResponse(
  39. status_code=500,
  40. content={"code": 500, "message": str(exc), "data": None},
  41. )
  42. @app.exception_handler(RecordNotFoundError)
  43. async def record_not_found_handler(
  44. request: Request, exc: RecordNotFoundError
  45. ) -> JSONResponse:
  46. return JSONResponse(
  47. status_code=404,
  48. content={"code": 4041, "message": str(exc), "data": None},
  49. )