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}") class RecordNotFoundError(Exception): def __init__(self, record_id: str): self.record_id = record_id super().__init__(f"Export record '{record_id}' not found") # (异常类, HTTP 状态码, 响应 code 字段) _HANDLERS: list[tuple[type[Exception], int, int]] = [ (DocumentNotFoundError, 404, 404), (ContentTooLargeError, 413, 413), (ExportError, 500, 500), (RecordNotFoundError, 404, 4041), ] def register_exception_handlers(app: FastAPI) -> None: def _make_handler(http_status: int, code: int): async def handler(request: Request, exc: Exception) -> JSONResponse: return JSONResponse( status_code=http_status, content={"code": code, "message": str(exc), "data": None}, ) return handler for exc_class, http_status, code in _HANDLERS: app.add_exception_handler(exc_class, _make_handler(http_status, code))