Skip to content

Conversation

@dicksontsai
Copy link
Collaborator

Summary

  • Add exception classes for API errors (400, 401, 429, 529, etc.)
  • Raise exceptions instead of returning errors as text messages
  • Enable programmatic error handling

Problem

API errors from the Anthropic API were being returned as text messages in the chat stream, making it impossible to:

  • Implement retry logic for transient errors (529 Overloaded)
  • Detect authentication failures programmatically
  • Handle rate limiting (429) with backoff

Solution

  1. Added new exception classes:

    • APIError (base class)
    • AuthenticationError (for 401)
    • BillingError (for billing issues)
    • RateLimitError (for 429)
    • InvalidRequestError (for 400)
    • ServerError (for 500, 529)
  2. Check AssistantMessage.error field and raise appropriate exceptions

Usage

from claude_agent_sdk import query, RateLimitError, InvalidRequestError

try:
    async for msg in query(prompt="test"):
        ...
except RateLimitError:
    # Implement retry logic
except InvalidRequestError as e:
    print(f"Invalid request: {e.error_text}")

Test plan

  • Added tests for all new exception classes
  • Added tests for error raising in client
  • All existing tests pass (131 tests)
  • Linting passes

Closes #472

API errors (400, 401, 429, 529) were being returned as text messages in
the chat stream, making programmatic error handling impossible.

Changes:
- Add new exception classes in _errors.py:
  - APIError (base class)
  - AuthenticationError (for authentication_failed)
  - BillingError (for billing_error)
  - RateLimitError (for rate_limit)
  - InvalidRequestError (for invalid_request)
  - ServerError (for server_error)
- Check AssistantMessage.error field and raise appropriate exceptions
- Export new exceptions from main module
- Add comprehensive tests

Users can now handle API errors programmatically:

```python
from claude_agent_sdk import query, RateLimitError, InvalidRequestError

try:
    async for msg in query(prompt="test"):
        ...
except RateLimitError:
    # Implement retry logic
except InvalidRequestError as e:
    print(f"Invalid request: {e.error_text}")
```

Closes #472

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] API errors are returned as text messages instead of raised as exceptions

2 participants