Register shared exception handlers.
(app: FastAPI)
| 78 | |
| 79 | |
| 80 | def install_exception_handlers(app: FastAPI) -> None: |
| 81 | """Register shared exception handlers.""" |
| 82 | |
| 83 | @app.exception_handler(GlmDeskError) |
| 84 | async def handle_glm_desk_error(request: Request, exc: GlmDeskError) -> JSONResponse: |
| 85 | logger.warning("application error on %s: %s", request.url.path, exc.message) |
| 86 | account_id = str(request.path_params.get("account_id") or "").strip() |
| 87 | runtime_logs = get_runtime_log_service() |
| 88 | if account_id: |
| 89 | runtime_logs.log_account_event( |
| 90 | account_id=account_id, |
| 91 | action="request", |
| 92 | stage="http_error", |
| 93 | status="failed", |
| 94 | message=exc.message, |
| 95 | details={"path": request.url.path, "code": exc.code, "details": exc.details}, |
| 96 | level=logging.WARNING, |
| 97 | ) |
| 98 | else: |
| 99 | runtime_logs.log_system_event( |
| 100 | stage="http_error", |
| 101 | status="failed", |
| 102 | message=exc.message, |
| 103 | details={"path": request.url.path, "code": exc.code, "details": exc.details}, |
| 104 | level=logging.WARNING, |
| 105 | ) |
| 106 | return JSONResponse(status_code=exc.status_code, content=exc.to_payload()) |
| 107 | |
| 108 | @app.exception_handler(Exception) |
| 109 | async def handle_unexpected_error(request: Request, exc: Exception) -> JSONResponse: |
| 110 | logger.exception("unexpected error on %s: %s", request.url.path, exc) |
| 111 | account_id = str(request.path_params.get("account_id") or "").strip() |
| 112 | runtime_logs = get_runtime_log_service() |
| 113 | details = {"path": request.url.path, "type": exc.__class__.__name__} |
| 114 | if account_id: |
| 115 | runtime_logs.log_account_event( |
| 116 | account_id=account_id, |
| 117 | action="request", |
| 118 | stage="http_error", |
| 119 | status="failed", |
| 120 | message="服务内部异常", |
| 121 | details=details, |
| 122 | level=logging.ERROR, |
| 123 | ) |
| 124 | else: |
| 125 | runtime_logs.log_system_event( |
| 126 | stage="http_error", |
| 127 | status="failed", |
| 128 | message="服务内部异常", |
| 129 | details=details, |
| 130 | level=logging.ERROR, |
| 131 | ) |
| 132 | payload = GlmDeskError( |
| 133 | "服务内部异常", |
| 134 | status_code=500, |
| 135 | code="internal_error", |
| 136 | details={"type": exc.__class__.__name__}, |
| 137 | ).to_payload() |