Error Handling & Retries
Relevant source files
The following files were used as context for generating this wiki page:
The Anthropic Go SDK provides a robust error handling framework designed to surface API-side issues, validation errors, and timeout conditions to the developer in a structured format. It utilizes Go's standard error wrapping patterns and provides specialized types to distinguish between different categories of failures, such as rate limits, authentication issues, and overloaded server states.
Beyond basic error reporting, the SDK includes sophisticated mechanisms for handling specific failure modes, including calculated timeouts based on token usage and automated error recovery within specialized modules like the Tool Runner.
Core Error Architecture
Errors originating from the API are encapsulated in the apierror.Error struct. This structure captures the full context of a failed request, including the HTTP status code, the original request, the raw response, and a unique RequestID extracted from the response headers.
The Error() method generates a descriptive string containing the HTTP method, URL, status code, and the Request ID if available. Developers can use DumpRequest and DumpResponse to inspect the full wire traffic for debugging purposes.
Sources: internal/apierror/apierror.go:14-53, internal/requestconfig/requestconfig_test.go:30-66
Error Types and Aliases
The SDK categorizes errors using the ErrorType constant. These are aliased in the package root to provide a clean public API for error checking.
| Error Type Constant | Description |
|---|---|
ErrorTypeInvalidRequestError | The request was malformed or contained invalid parameters. |
ErrorTypeAuthenticationError | API key is missing, invalid, or lacks necessary permissions. |
ErrorTypePermissionError | The authenticated user does not have permission for the specific resource. |
ErrorTypeNotFoundError | The requested resource (e.g., a specific model or file) was not found. |
ErrorTypeRateLimitError | Too many requests have been made in a given timeframe. |
ErrorTypeTimeoutError | The request exceeded the server-side or client-side timeout. |
ErrorTypeOverloadedError | Anthropic's servers are currently experiencing high traffic. |
ErrorTypeAPIError | A generic server-side error occurred. |
ErrorTypeBillingError | Issues related to the account's billing status. |
Sources: aliases.go:24-70, shared/constant/constants.go:68-85
Timeout Logic & Token Limits
The SDK implements proactive error prevention by calculating timeouts based on the MaxTokens parameter for non-streaming requests. If a request is likely to exceed standard processing times, the SDK will either adjust the timeout or return an error before the request is even sent.
The function CalculateNonStreamingTimeout is responsible for this logic, ensuring that large token requests are granted sufficient time while preventing runaway processes that exceed known model capabilities.
Sources: message_test.go:490-607, shared/constant/constants.go:10-21
Tool Runner Error Recovery
The BetaToolRunner provides an automated conversation loop that includes built-in error handling for tool execution. When a model requests a tool call that fails during execution, the runner does not simply crash; instead, it captures the error and feeds it back to the model.
Tool Execution Flow
- The model emits a
tool_useblock. - The SDK executes the handler associated with that tool.
- If the handler returns an
error, the SDK creates atool_resultwithis_error: true. - This result is appended to the message history and sent back to the model, allowing the model to attempt a correction or explain the failure.
This mechanism ensures that transient tool failures or validation errors in user-defined handlers are handled gracefully within the context of the AI conversation.
Sources: toolrunner/runner_test.go:197-258, tools.md:144-159
Request Tracing
For enterprise-grade error tracking, the SDK extracts the request-id header from every API response. This ID is essential when contacting Anthropic support regarding specific failed requests.
// Example of accessing the Request ID from an error
if err != nil {
var apiErr *anthropic.Error
if errors.As(err, &apiErr) {
fmt.Printf("Error occurred. Request ID: %s\n", apiErr.RequestID)
}
}
Sources: internal/apierror/apierror.go:42-45, internal/requestconfig/requestconfig_test.go:58-66
Summary
The Anthropic Go SDK's error handling system is built on the principle of transparency and resilience. By surfacing detailed metadata through apierror.Error and providing automated recovery loops in the toolrunner, the SDK allows developers to build applications that can reliably handle API constraints and runtime failures. The inclusion of token-based timeout calculations further protects applications from unpredictable latency in non-streaming scenarios.