from fastapi import FastAPI, Request from fastapi.responses import JSONResponse class DocumentNotFoundError(Exception): def __init__(self, document_id: str): self.document_id = document_id super().__init__(f"Document '{document_id}' not found") class ContentTooLargeError(Exception): def __init__(self, size: int, limit: int = 200_000): super().__init__(f"Content size {size} bytes exceeds limit of {limit} bytes") class ExportError(Exception): def __init__(self, reason: str): super().__init__(f"Export failed: {reason}") def register_exception_handlers(app: FastAPI) -> None: @app.exception_handler(DocumentNotFoundError) async def document_not_found_handler( request: Request, exc: DocumentNotFoundError ) -> JSONResponse: return JSONResponse( status_code=404, content={"code": 404, "message": str(exc), "data": None}, ) @app.exception_handler(ContentTooLargeError) async def content_too_large_handler( request: Request, exc: ContentTooLargeError ) -> JSONResponse: return JSONResponse( status_code=413, content={"code": 413, "message": str(exc), "data": None}, ) @app.exception_handler(ExportError) async def export_error_handler( request: Request, exc: ExportError ) -> JSONResponse: return JSONResponse( status_code=500, content={"code": 500, "message": str(exc), "data": None}, )