{"record":{"id":"407bb3edaa31d19b","repo":"microsoft/semantic-kernel","slug":"an-unexpected-error-occurred-while-getting-search","errorCode":null,"errorMessage":"An unexpected error occurred while getting search results.","messagePattern":"An unexpected error occurred while getting search results\\.","errorType":"exception","errorClass":"ServiceInvalidRequestError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/brave.py","lineNumber":241,"sourceCode":"\n        headers = {\n            \"X-Subscription-Token\": self.settings.api_key.get_secret_value(),\n            \"user_agent\": SEMANTIC_KERNEL_USER_AGENT,\n        }\n        try:\n            async with AsyncClient(timeout=5) as client:\n                response = await client.get(url, headers=headers, params=params)\n                response.raise_for_status()\n                return BraveSearchResponse.model_validate_json(response.text)\n        except HTTPStatusError as ex:\n            logger.error(f\"Failed to get search results: {ex}\")\n            raise ServiceInvalidRequestError(\"Failed to get search results.\") from ex\n        except RequestError as ex:\n            logger.error(f\"Client error occurred: {ex}\")\n            raise ServiceInvalidRequestError(\"A client error occurred while getting search results.\") from ex\n        except Exception as ex:\n            logger.error(f\"An unexpected error occurred: {ex}\")\n            raise ServiceInvalidRequestError(\"An unexpected error occurred while getting search results.\") from ex\n\n    def _validate_options(self, options: SearchOptions) -> None:\n        if options.top <= 0:\n            raise ServiceInvalidRequestError(\"count value must be greater than 0.\")\n        if options.top >= 21:\n            raise ServiceInvalidRequestError(\"count value must be less than 21.\")\n\n        if options.skip < 0:\n            raise ServiceInvalidRequestError(\"offset must be greater than or equal to 0.\")\n        if options.skip > 9:\n            raise ServiceInvalidRequestError(\"offset must be less than 10.\")\n\n    def _get_url(self) -> str:\n        return DEFAULT_URL\n\n    def _parse_filter_lambda(self, filter_lambda: Callable | str) -> list[dict[str, str]]:\n        \"\"\"Parse a string lambda or string expression into a list of {field: value} dicts using AST.\"\"\"\n        expr = filter_lambda if isinstance(filter_lambda, str) else getsource(filter_lambda).strip()","sourceCodeStart":223,"sourceCodeEnd":259,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/brave.py#L223-L259","documentation":"A catch-all ServiceInvalidRequestError for any exception during the Brave request that is neither an HTTPStatusError nor a RequestError. This guards against unexpected failures (e.g. JSON validation errors from model_validate_json, unexpected SDK exceptions) so the connector never leaks an unhandled exception to the caller.","triggerScenarios":"Calling search() and an exception other than HTTPStatusError or RequestError is raised inside the try block at brave.py:228-232 — most commonly a pydantic ValidationError thrown by BraveSearchResponse.model_validate_json when the response body does not match the expected schema, or an unexpected httpx/transport error type.","commonSituations":"The Brave API returns a malformed/unexpected JSON shape that fails pydantic validation, an unhandled httpx exception type, or a bug in response parsing.","solutions":["Inspect exc.__cause__ to identify the unexpected exception type and message.","If the cause is a pydantic ValidationError, the Brave API response schema may have changed — check for a connector version update.","For unknown transient causes, add a retry with limited attempts and log the underlying exception for diagnosis."],"exampleFix":"// before\nresults = await connector.search(query)\n// after\ntry:\n    results = await connector.search(query)\nexcept ServiceInvalidRequestError as e:\n    logger.exception(\"Brave unexpected error: %s\", e.__cause__)\n    raise\n","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"from semantic_kernel.exceptions import ServiceInvalidRequestError\n\ntry:\n    results = await connector.search(query)\nexcept ServiceInvalidRequestError as e:\n    logger.exception(\"Unexpected Brave search error: %s\", e.__cause__)\n    raise","preventionTips":["Log e.__cause__ to diagnose unexpected failures (often pydantic schema mismatch).","Keep the connector version current to match the Brave response schema.","Add bounded retry for transient unexpected errors."],"tags":["brave","network","http","unexpected"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}