exceptions.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. # (异常类, HTTP 状态码, 响应 code 字段)
  18. _HANDLERS: list[tuple[type[Exception], int, int]] = [
  19. (DocumentNotFoundError, 404, 404),
  20. (ContentTooLargeError, 413, 413),
  21. (ExportError, 500, 500),
  22. (RecordNotFoundError, 404, 4041),
  23. ]
  24. def register_exception_handlers(app: FastAPI) -> None:
  25. def _make_handler(http_status: int, code: int):
  26. async def handler(request: Request, exc: Exception) -> JSONResponse:
  27. return JSONResponse(
  28. status_code=http_status,
  29. content={"code": code, "message": str(exc), "data": None},
  30. )
  31. return handler
  32. for exc_class, http_status, code in _HANDLERS:
  33. app.add_exception_handler(exc_class, _make_handler(http_status, code))