{"record":{"id":"69c9c9fd5cf3c796","repo":"microsoft/semantic-kernel","slug":"exception-occurred-while-fetching-token","errorCode":null,"errorMessage":"Exception occurred while fetching token.","messagePattern":"Exception occurred while fetching token\\.","errorType":"exception","errorClass":"AgentInvokeException","httpStatus":null,"severity":"error","filePath":"python/samples/demos/copilot_studio_agent/src/direct_line_agent.py","lineNumber":81,"sourceCode":"                            logger.error(\"Token generation response missing token: %s\", data)\n                            raise AgentInvokeException(\"No token received from token generation.\")\n                    else:\n                        logger.error(\"Token generation endpoint error status: %s\", resp.status)\n                        raise AgentInvokeException(\"Failed to generate token using bot_secret.\")\n            else:\n                async with self.session.get(self.token_endpoint) as resp:\n                    if resp.status == 200:\n                        data = await resp.json()\n                        self.directline_token = data.get(\"token\")\n                        if not self.directline_token:\n                            logger.error(\"Token endpoint returned no token: %s\", data)\n                            raise AgentInvokeException(\"No token received.\")\n                    else:\n                        logger.error(\"Token endpoint error status: %s\", resp.status)\n                        raise AgentInvokeException(\"Failed to fetch token from token endpoint.\")\n        except Exception as ex:\n            logger.exception(\"Exception fetching token: %s\", ex)\n            raise AgentInvokeException(\"Exception occurred while fetching token.\") from ex\n\n    @trace_agent_get_response\n    @override\n    async def get_response(\n        self,\n        history: ChatHistory,\n        arguments: dict[str, Any] | None = None,\n        **kwargs: Any,\n    ) -> ChatMessageContent:\n        \"\"\"\n        Get a response from the DirectLine Bot.\n        \"\"\"\n        responses = []\n        async for response in self.invoke(history, arguments, **kwargs):\n            responses.append(response)\n\n        if not responses:\n            raise AgentInvokeException(\"No response from DirectLine Bot.\")","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/samples/demos/copilot_studio_agent/src/direct_line_agent.py#L63-L99","documentation":"A catch-all AgentInvokeException wrapping any unexpected Exception during the token-fetch flow (both branches). It logs the original via logger.exception and re-raises with 'from ex' to preserve the chain. This handles non-HTTP failures like connection errors, timeouts, JSON decode errors, or DNS failures that escape the status checks.","triggerScenarios":"Any exception other than the handled status/missing-token cases: aiohttp ClientError, asyncio.TimeoutError, JSONDecodeError on a non-JSON 200 body, DNS resolution failure, etc.","commonSituations":"Network unreachable; proxy/firewall blocking the endpoint; response wasn't valid JSON; SSL certificate problem; the aiohttp session was closed.","solutions":["Read the chained exception (the `from ex` original) — it carries the real cause (timeout, connection reset, etc.).","Fix the underlying network/connectivity issue; verify DNS and TLS to the endpoint.","Add a timeout to the session/requests to fail fast and distinguish timeouts from other errors."],"exampleFix":"// before\nexcept Exception as ex:\n    logger.exception(\"Exception fetching token: %s\", ex)\n    raise AgentInvokeException(\"Exception occurred while fetching token.\") from ex\n\n// after  # surface the specific cause for diagnosis\nexcept (aiohttp.ClientError, asyncio.TimeoutError) as ex:\n    logger.exception(\"Network error fetching token: %s\", ex)\n    raise AgentInvokeException(f\"Network error fetching token: {ex}\") from ex","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    await fetch_token()\nexcept AgentInvokeException as e:\n    logger.exception(\"Token fetch failed: %s\", e.__cause__)\n    raise","preventionTips":["Always inspect e.__cause__ — the wrapped exception carries the real network/decode failure.","Set aiohttp timeouts so connection stalls surface as TimeoutError, not hangs."],"tags":["network","error-handling","directline","copilot-studio","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}