| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- from fastapi import FastAPI, Request
- from fastapi.responses import JSONResponse
- class DocumentNotFoundError(Exception):
- def __init__(self, document_id: str):
- super().__init__(f"Document '{document_id}' not found")
- class DocumentParseError(Exception):
- """Word 下载或解析失败。"""
- pass
- class ExportError(Exception):
- pass
- class RecordNotFoundError(Exception):
- def __init__(self, record_id: str):
- super().__init__(f"Export record '{record_id}' not found")
- _HANDLERS: list[tuple[type[Exception], int, int]] = [
- (DocumentNotFoundError, 404, 404),
- (DocumentParseError, 400, 400),
- (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))
|