Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(py): make HTTP status errors catchable as `ComposioError` on client 2.0 (#4556)

Alberto Schiabelb2f5098b28e9
diff --git a/python/composio/client/__init__.py b/python/composio/client/__init__.py
index 027613534..bb0ff6de6 100644
--- a/python/composio/client/__init__.py
+++ b/python/composio/client/__init__.py
@@ -15,16 +15,87 @@ from composio_client import (
DEFAULT_MAX_RETRIES,
NOT_GIVEN,
APIError,
+ APIStatusError,
NotGiven,
)
from composio_client import Composio as BaseComposio
-from httpx import URL, Client, Request, Timeout
+from httpx import URL, Client, Request, Response, Timeout
+from composio.exceptions import ComposioError
from composio.utils.logging import LogLevel, WithLogger, _VerbosityWrapper
ComposioAPIError = APIError
APIEnvironment = te.Literal["production", "staging", "local"]
+
+_SDK_ERROR_CLASSES: t.Dict[t.Type[APIStatusError], t.Type[APIStatusError]] = {}
+
+
+def _with_sdk_error_base(
+ error_class: t.Type[APIStatusError],
+) -> t.Type[APIStatusError]:
+ """
+ Return a subclass of a generated-client status error that also derives
+ from the SDK's ``ComposioError``.
+
+ The generated client has its own exception root, unrelated to
+ ``composio.exceptions.ComposioError``, so HTTP failures such as an invalid
+ API key used to escape ``except ComposioError``. Keeping the generated
+ class as the first base preserves its constructor, ``status_code`` and
+ ``isinstance`` checks, so existing ``except APIStatusError`` handlers keep
+ working unchanged.
+ """
+ cached = _SDK_ERROR_CLASSES.get(error_class)
+ if cached is not None:
+ return cached
+ sdk_class = t.cast(
+ t.Type[APIStatusError],
+ type(
+ error_class.__name__,
+ (error_class, ComposioError),
+ {
+ "__module__": error_class.__module__,
+ "__reduce__": _reduce_sdk_error,
+ },
+ ),
+ )
+ # setdefault keeps the first class if two threads race to build one.
+ return _SDK_ERROR_CLASSES.setdefault(error_class, sdk_class)
+
+
+def _reduce_sdk_error(self: APIStatusError) -> t.Tuple[t.Any, ...]:
+ """
+ Pickle support for the classes built by ``_with_sdk_error_base``.
+
+ They are not module attributes, so pickle cannot find them by name. Record
+ the generated class instead and rebuild the SDK subclass on load.
+ """
+ error_class = type(self).__mro__[1]
+ return (
+ _rebuild_sdk_error,
+ (error_class, self.message, self.response, self.body),
+ self.__dict__,
+ )
+
+
+def _rebuild_sdk_error(
+ error_class: t.Type[APIStatusError],
+ message: str,
+ response: Response,
+ body: object,
+) -> APIStatusError:
+ return _with_sdk_error_base(error_class)(message, response=response, body=body)
+
+
+def _as_sdk_error(error: APIStatusError) -> APIStatusError:
+ if isinstance(error, ComposioError):
+ return error
+ sdk_error = _with_sdk_error_base(type(error))(
+ error.message, response=error.response, body=error.body
+ )
+ return sdk_error.with_traceback(error.__traceback__)
+
+
CLIENT_LOGGER_NAME = "composio_client"
"""Name of the logger the generated ``composio_client`` package writes to."""
@@ -314,6 +385,28 @@ class HttpClient(BaseComposio, WithLogger):
self._without_retries = self.with_options(max_retries=0)
return self._without_retries
+ def _decode(self, response: Response) -> t.Any:
+ """
+ Raise status errors that are also ``ComposioError``s; see
+ ``_with_sdk_error_base``.
+ """
+ try:
+ return super()._decode(response)
+ except APIStatusError as error:
+ raise _as_sdk_error(error) from None
+
+ def _process_response(
+ self, response: Response, cast_to: t.Optional[t.Type[t.Any]]
+ ) -> t.Any:
+ """
+ Raise status errors that are also ``ComposioError``s; see
+ ``_with_sdk_error_base``.
+ """
+ try:
+ return super()._process_response(response, cast_to)
+ except APIStatusError as error:
+ raise _as_sdk_error(error) from None
+
def _prepare_request(self, request: Request) -> None:
"""
Request interceptor to inject request id, provider, and SDK version.
diff --git a/python/tests/test_client_errors.py b/python/tests/test_client_errors.py
new file mode 100644
index 000000000..4e69630b5
--- /dev/null
+++ b/python/tests/test_client_errors.py
@@ -0,0 +1,170 @@
+"""HTTP status errors from the generated client must be ``ComposioError``s.
+
+The generated client (``composio_client``) has its own exception root, so an
+invalid API key or any other 4xx/5xx response used to escape
+``except ComposioError`` (issue #4537). ``HttpClient`` now builds those errors
+as subclasses of both the generated class and ``ComposioError``, so SDK callers
+can catch one root while existing ``except APIStatusError`` handlers, including
+the SDK's own, keep working.
+"""
+
+import copy
+import pickle
+import typing as t
+from unittest.mock import Mock
+
+import composio_client
+import httpx
+import pytest
+
+from composio import exceptions
+from composio.client import HttpClient
+from composio.core.models.base import allow_tracking
+from composio.core.models.tools import Tools
+from composio.core.models.triggers import Triggers
+
+
[email protected](autouse=True)
+def disable_telemetry():
+ """Disable telemetry for all tests to prevent thread issues."""
+ token = allow_tracking.set(False)
+ yield
+ allow_tracking.reset(token)
+
+
+def _client_returning(
+ status: int,
+ *,
+ max_retries: int = 0,
+ calls: t.Optional[t.List[httpx.Request]] = None,
+) -> HttpClient:
+ def handler(request: httpx.Request) -> httpx.Response:
+ if calls is not None:
+ calls.append(request)
+ return httpx.Response(
+ status,
+ json={"error": {"message": "nope"}},
+ # Keep retry backoff short in tests.
+ headers={"retry-after-ms": "1"},
+ )
+
+ return HttpClient(
+ provider="test",
+ api_key="sk-test",
+ base_url="https://backend.invalid",
+ max_retries=max_retries,
+ http_client=httpx.Client(transport=httpx.MockTransport(handler)),
+ )
+
+
+ ("status", "client_error"),
+ [
+ (400, composio_client.BadRequestError),
+ (401, composio_client.AuthenticationError),
+ (403, composio_client.PermissionDeniedError),
+ (404, composio_client.NotFoundError),
+ (409, composio_client.ConflictError),
+ (422, composio_client.UnprocessableEntityError),
+ (429, composio_client.RateLimitError),
+ (500, composio_client.InternalServerError),
+ (418, composio_client.APIStatusError),
+ ],
+)
+def test_status_errors_are_composio_errors(
+ status: int, client_error: t.Type[composio_client.APIStatusError]
+) -> None:
+ client = _client_returning(status)
+
+ with pytest.raises(exceptions.ComposioError) as exc_info:
+ client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
+
+ error = exc_info.value
+ assert isinstance(error, client_error)
+ assert isinstance(error, composio_client.APIStatusError)
+ assert error.status_code == status
+ assert error.message
+
+
+def test_invalid_api_key_is_catchable_as_composio_error() -> None:
+ client = _client_returning(401)
+
+ try:
+ client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
+ except exceptions.ComposioError as error:
+ assert isinstance(error, composio_client.AuthenticationError)
+ else:
+ pytest.fail("expected the 401 to raise")
+
+
+def test_error_classes_are_reused_across_requests() -> None:
+ client = _client_returning(401)
+ raised = []
+ for _ in range(2):
+ with pytest.raises(composio_client.AuthenticationError) as exc_info:
+ client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
+ raised.append(type(exc_info.value))
+
+ assert raised[0] is raised[1]
+ assert raised[0].__name__ == "AuthenticationError"
+
+
+def test_schema_fetch_auth_error_is_a_composio_error() -> None:
+ tools = Tools(client=_client_returning(401), provider=Mock())
+
+ with pytest.raises(composio_client.AuthenticationError) as exc_info:
+ tools.get_raw_composio_tool_by_slug("SLACK_FETCH_CONVERSATION_HISTORY")
+
+ assert isinstance(exc_info.value, exceptions.ComposioError)
+ assert not isinstance(exc_info.value, exceptions.ToolNotFoundError)
+
+
+def test_trigger_type_not_found_mapping_still_applies() -> None:
+ triggers = Triggers(client=_client_returning(404))
+
+ with pytest.raises(exceptions.TriggerTypeNotFound) as exc_info:
+ triggers.create(slug="NONEXISTENT_TRIGGER", user_id="user")
+
+ assert isinstance(exc_info.value.__cause__, composio_client.NotFoundError)
+
+
+def test_without_retries_client_raises_composio_error() -> None:
+ client = _client_returning(401)
+
+ with pytest.raises(exceptions.ComposioError) as exc_info:
+ client.without_retries.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
+
+ assert isinstance(exc_info.value, composio_client.AuthenticationError)
+
+
+def test_error_after_exhausted_retries_is_composio_error() -> None:
+ calls: t.List[httpx.Request] = []
+ client = _client_returning(503, max_retries=2, calls=calls)
+
+ with pytest.raises(exceptions.ComposioError) as exc_info:
+ client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
+
+ assert isinstance(exc_info.value, composio_client.InternalServerError)
+ assert len(calls) == 3
+
+
+ "clone",
+ [lambda error: pickle.loads(pickle.dumps(error)), copy.deepcopy],
+ ids=["pickle", "deepcopy"],
+)
+def test_status_errors_survive_serialization(
+ clone: t.Callable[[BaseException], BaseException],
+) -> None:
+ client = _client_returning(401)
+ with pytest.raises(exceptions.ComposioError) as exc_info:
+ client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
+ error = exc_info.value
+
+ restored = clone(error)
+
+ assert type(restored) is type(error)
+ assert isinstance(restored, composio_client.AuthenticationError)
+ assert isinstance(restored, exceptions.ComposioError)
+ assert t.cast(composio_client.APIStatusError, restored).status_code == 401
+ assert str(restored) == str(error)