Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I handle errors and exceptions when using the Anthropic Python SDK
    Anthropic Python SDK error handling exceptions APIConnectionError APIStatusError BadRequestError AuthenticationError PermissionDeniedError NotFoundError UnprocessableEntityError RateLimitError InternalServerError


How do I handle errors and exceptions when using the Anthropic Python SDK


To handle errors and exceptions when using the Anthropic Python SDK, you can catch specific exception types raised by the library[1][4]:

- `anthropic.APIConnectionError`: Raised when the library is unable to connect to the API, for example due to network connection problems or a timeout[4].

- `anthropic.APIStatusError`: Raised when the API returns a non-success status code (4xx or 5xx). It contains `status_code` and `response` properties[4].

- `anthropic.BadRequestError`: Raised for 400 Bad Request errors[4].

- `anthropic.AuthenticationError`: Raised for 401 Unauthorized errors[4].

- `anthropic.PermissionDeniedError`: Raised for 403 Forbidden errors[4].

- `anthropic.NotFoundError`: Raised for 404 Not Found errors[4].

- `anthropic.UnprocessableEntityError`: Raised for 422 Unprocessable Entity errors[4].

- `anthropic.RateLimitError`: Raised for 429 Too Many Requests errors[4].

- `anthropic.InternalServerError`: Raised for 500+ Internal Server errors[4].

Here's an example of how to catch these exceptions:

python
import anthropic

client = anthropic.Anthropic()

try:
    response = client.completions.create(
        prompt=f"{anthropic.HUMAN_PROMPT} Your prompt here{anthropic.AI_PROMPT}",
        max_tokens_to_sample=300,
        model="claude-2"
    )
except anthropic.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx
except anthropic.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except anthropic.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

By catching these exceptions, you can handle specific error scenarios and provide appropriate error messages or fallback behavior in your application[1][4].

Citations:
[1] https://github.com/anthropics/anthropic-sdk-python/actions/runs/8370175174
[2] https://docs.anthropic.com/en/api/client-sdks
[3] https://www.datacamp.com/tutorial/getting-started-with-the-claude-2-and-the-claude-2-api
[4] https://pypi.org/project/anthropic/0.3.9/
[5] https://pypi.org/project/anthropic/0.2.8/