Follow Discord
Sweep 24 Nov 2026 · 22:58Z Build v2.1.332 549 read Stable v2.1.326 Latest v2.1.332 Next v2.1.332 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · api

One read of Claude Developer Platformapi-20261125T043708Z

11 pages moved out of 965 read.

Pages moved 11 significant first
Pages read 965 in this capture
Captured 04:37 UTC
Corpus hash 9a8048a05311 corpus-hash

What this read moved

1-11 of 11

api/errors Changed · +249 / -8 lines

### Retries ### Error codes

from line 4
44description: Understand the HTTP status codes, error response shape, and request IDs the Claude API returns, and handle errors with the SDK's typed exceptions.
55---
66 
7To find the SDK error that an API error becomes, see [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types). To catch it in your code, see [Handle errors](https://platform.claude.com/docs/en/api/handle-errors).
8 
79## HTTP errors
810 
911The API follows a predictable HTTP error code format:
from line 36
3436 
3537* 429 - `rate_limit_error`: Your organization has hit a [rate limit](https://platform.claude.com/docs/en/api/rate-limits), reached its usage tier’s monthly spend cap, or reached a spend limit on the Claude Code workspace. A tier spend-cap 429 has no `retry-after` header and keeps failing until access resumes; see [Reaching your spend cap](https://platform.claude.com/docs/en/api/rate-limits#reaching-your-spend-cap) for how to recognize it. A sharp increase in usage can also cause a 429 even while you’re under your rate limits; see [Ramp limits](https://platform.claude.com/docs/en/api/rate-limits#ramp-limits).
3638 
37* 500 - `api_error`: An unexpected error has occurred internal to Anthropic’s systems. Retry the request with exponential backoff; if the error persists, contact support with the [request ID](https://platform.claude.com/docs/en/api/errors#request-id). If the error type is `timeout_error` instead, see the 504 entry.
39 To tell the spend cap from a rate limit in code, check the [error code](https://platform.claude.com/docs/en/api/errors#error-codes).
3840 
41* 500 - `api_error`: An unexpected error has occurred internal to Anthropic’s systems. Retry only if the response’s `x-should-retry` header isn’t `false` (see [Retries](https://platform.claude.com/docs/en/api/errors#retries)). If the error persists, contact support with the [request ID](https://platform.claude.com/docs/en/api/errors#request-id). If the error type is `timeout_error` instead, see the 504 entry.
42 
3943* 504 - `timeout_error`: The request timed out while processing. The API also returns `timeout_error` with other status codes, such as a 500 when a request reaches the server’s time limit before the response starts. For long-running Messages API requests, use the [streaming Messages API](https://platform.claude.com/docs/en/build-with-claude/streaming). See [Long requests](https://platform.claude.com/docs/en/api/errors#long-requests) for more options.
4044 
4145* 529 - `overloaded_error`: The API is temporarily overloaded.
from line 48
4448 A 529 error can occur when the API experiences high traffic across all users.
4549 </Warning>
4650 
47The official SDK automatically retries transient failures (such as connection errors, rate limits, and 5xx server errors) with exponential backoff, twice by default, honoring the `retry-after` header when present. The SDK client accepts `max_retries` (typescript, php: `maxRetries`; java: `.maxRetries()`; csharp: `MaxRetries`; go: `option.WithMaxRetries()`) to configure or disable this behavior.
48 
4951When receiving a [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) response over server-sent events (SSE), an error can occur after the API returns a 200 response. In that case, error handling doesn’t follow these standard mechanisms. See [Error events](https://platform.claude.com/docs/en/build-with-claude/streaming#error-events) for the shape of mid-stream errors.
5052 
53The SDK doesn’t retry an error in a stream. To catch one, see [Handle an error in a stream](https://platform.claude.com/docs/en/api/handle-errors#handle-an-error-in-a-stream).
54 
55### Retries
56 
57By default, the SDK retries a failed request up to two times (three attempts in all). To change the number of retries, set `max_retries` (typescript, php: `maxRetries`; java: `.maxRetries()`; csharp: `MaxRetries`; go: `option.WithMaxRetries()`) on the client. A value of `0` turns retries off.
58 
59For each failed attempt, the SDK determines two things:
60 
61* **Whether the SDK retries:** If the response has an `x-should-retry` header (`true` or `false`), the SDK follows it. Otherwise, the SDK retries connection errors, timeouts, and the statuses 408, 409, 429, and 500 and above.
62* **How long the SDK waits:** If the response has a `retry-after` header, the SDK waits as long as the header says. Otherwise, it uses exponential backoff from 0.5 to 8 seconds.
63 
64The Go SDK retries some create methods in fewer cases. See [Retries for create methods in the Go SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go#retries-for-create-methods).
65 
66Without the SDK, follow `x-should-retry` and `retry-after` in your own code and use backoff and a retry limit.
67 
5168## Request size limits
5269 
5370The first-party Claude API enforces these request size limits. For other platforms, see the [API overview](https://platform.claude.com/docs/en/api/overview#request-size-limits).
from line 95
7895 
7996Under the [API versioning policy](https://platform.claude.com/docs/en/api/versioning), the values within these objects can expand, and new `type` values can appear.
8097 
98### Error codes
99 
100Some errors also have an error code in `error.details.error_code`. One `type` can cover several causes, and a code names one of them.
101 
102For example, hitting a rate limit and reaching your [monthly spend cap](https://platform.claude.com/docs/en/api/rate-limits#reaching-your-spend-cap) both cause a 429 `rate_limit_error`. On the Messages API, the spend-cap response adds a code:
103 
104```json JSON
105{
106 "type": "error",
107 "error": {
108 "type": "rate_limit_error",
109 "message": "You have reached your API usage limits: ...",
110 "details": { "error_code": "enforced_spend_limit_reached" }
111 },
112 "request_id": "req_018EeWyXxfu5pfWkrYcMdjWG"
113}
114```
115 
116Other APIs that return this 429, such as Claude Managed Agents, don’t add the code. There, only the `message` tells the two causes apart, and you shouldn’t match it in code. A spend-cap 429 keeps failing until access resumes, so limit your retries after a 429.
117 
118The set of codes can grow. If an error has no code or has a code that you don’t recognize, handle it by its `type` or HTTP status.
119 
120For the full list of codes, see [`ErrorDetails`](https://platform.claude.com/docs/en/api/$shared#error_details) in the API reference. To find the codes that a method can return, see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code).
121 
81122## SDK error types
82123 
83The official SDK raises typed exceptions for these errors instead of returning raw JSON. For example, a 404 surfaces as `anthropic.NotFoundError` (typescript: `Anthropic.NotFoundError`; ruby: `Anthropic::Errors::NotFoundError`; java: `com.anthropic.errors.NotFoundException`; csharp: `AnthropicNotFoundException`; php: `Anthropic\Core\Exceptions\NotFoundException`; go: `*anthropic.Error`). The Go SDK has one error type for every status, `*anthropic.Error`: branch on `StatusCode`. Catch the SDK’s typed classes rather than string-matching error messages, handling the most specific classes first. Your SDK’s page documents the full exception hierarchy:
124This section lists what to catch or check in the SDK for each kind of error. To write a handler, see [Handle errors](https://platform.claude.com/docs/en/api/handle-errors).
84125 
85* [Python](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#handling-errors) · [TypeScript](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript#handling-errors) · [C#](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/csharp#error-handling) · [Go](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go#error-handling) · [Java](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#error-handling) · [PHP](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/php#error-handling) · [Ruby](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/ruby#handling-errors)
126<Tabs>
127 <Tab title="Python">
128 These classes are in the `anthropic` package unless a row names another. A class also catches its subclasses, so put the narrower class first. For example, `RateLimitError` also catches `EnforcedSpendLimitReachedError`.
86129 
130 | To handle | Catch |
131 | ----- | ----- |
132 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | Its own class, such as `anthropic.EnforcedSpendLimitReachedError` (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)) |
133 | 400 | `BadRequestError` |
134 | 401 | `AuthenticationError` |
135 | 403 | `PermissionDeniedError` |
136 | 404 | `NotFoundError` |
137 | 409 | `ConflictError` |
138 | 413 | `ContentTooLargeError` |
139 | 422 | `UnprocessableEntityError` |
140 | 429 | `RateLimitError` |
141 | 504 | `GatewayTimeoutError` |
142 | 529 | `OverloadedError` |
143 | Every 5xx, such as 500, 504, and 529 | `InternalServerError` |
144 | Every error response | `APIStatusError` |
145 | An error event in a stream | `APIStatusError` |
146 | A client timeout (the SDK stopped waiting) | `APITimeoutError` |
147 | Every connection failure before a response arrives (including a client timeout) | `APIConnectionError` |
148 | A connection that drops or stalls in mid-stream | `httpx2.TransportError` (`httpx2` is the SDK’s HTTP library) |
149 | Every error in this table except a dropped stream | `APIError` |
150 
151 For a status that has no row, such as 402, catch `APIStatusError` and compare its `status_code`.
152 
153 To reach the underlying exception or the raw response, see [Handling errors in Python](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#handling-errors).
154 </Tab>
155 
156 <Tab title="TypeScript">
157 These classes are properties of `Anthropic` unless a row says otherwise. A class also catches its subclasses, so put the narrower class first. For example, `RateLimitError` also catches `EnforcedSpendLimitReachedError`.
158 
159 | To handle | Catch |
160 | ----- | ----- |
161 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | Its own class, such as `Anthropic.EnforcedSpendLimitReachedError` (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)) |
162 | 400 | `BadRequestError` |
163 | 401 | `AuthenticationError` |
164 | 403 | `PermissionDeniedError` |
165 | 404 | `NotFoundError` |
166 | 409 | `ConflictError` |
167 | 413 | `ContentTooLargeError` |
168 | 422 | `UnprocessableEntityError` |
169 | 429 | `RateLimitError` |
170 | 504 | `GatewayTimeoutError` |
171 | 529 | `OverloadedError` |
172 | Every 5xx, such as 500, 504, and 529 | `InternalServerError` |
173 | A client timeout (the SDK stopped waiting) | `APIConnectionTimeoutError` |
174 | Every connection failure before a response arrives (including a client timeout) | `APIConnectionError` |
175 | A connection that drops in mid-stream | `AnthropicError` from `client.messages.stream()`. With `stream: true`, catch the runtime’s own error, such as `TypeError`. |
176 | An error event in a stream | `APIError` |
177 | Every error in this table except a dropped stream | `APIError` |
178 
179 For a status that has no row, such as 402, catch `APIError` and compare its `status`.
180 
181 To read the response headers, see [Handling errors in TypeScript](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript#handling-errors).
182 </Tab>
183 
184 <Tab title="C#">
185 These classes are in the `Anthropic.Exceptions` namespace unless a row names another. A class also catches its subclasses, so put the narrower class first. For example, `AnthropicRateLimitException` also catches `AnthropicEnforcedSpendLimitReachedException`.
186 
187 | To handle | Catch |
188 | ----- | ----- |
189 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | Its own class, such as `Anthropic.Models.AnthropicEnforcedSpendLimitReachedException` (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)) |
190 | 400 | `AnthropicBadRequestException` |
191 | 401 | `AnthropicUnauthorizedException` |
192 | 403 | `AnthropicForbiddenException` |
193 | 404 | `AnthropicNotFoundException` |
194 | 409 | `AnthropicConflictException` |
195 | 413 | `AnthropicContentTooLargeException` |
196 | 422 | `AnthropicUnprocessableEntityException` |
197 | 429 | `AnthropicRateLimitException` |
198 | 504 | `AnthropicGatewayTimeoutException` |
199 | 529 | `AnthropicOverloadedException` |
200 | Every 4xx | `Anthropic4xxException` |
201 | Every 5xx, such as 500, 504, and 529 | `Anthropic5xxException` |
202 | Every error response | `AnthropicApiException` |
203 | An error event in a stream | `AnthropicSseException` |
204 | Every error response and every error event in a stream | `AnthropicServiceException` |
205 | A connection failure before a response arrives | `AnthropicIOException` |
206 | A connection that drops in mid-stream | .NET’s own `IOException` in `System.IO` |
207 | A client timeout (the SDK stopped waiting) | .NET’s own `TaskCanceledException` in `System.Threading.Tasks` |
208 | Every error in this table except a client timeout and a dropped stream | `AnthropicException` |
209 
210 For a status that has no row of its own, such as 402, catch `Anthropic4xxException` and compare its `StatusCode`.
211 </Tab>
212 
213 <Tab title="Go">
214 The Go SDK has one error type, `*anthropic.Error`. You compare its fields instead of catching a class. In this table, `apierr` is a `*anthropic.Error` variable that `errors.As()` fills.
215 
216 | To handle | Check |
217 | ----- | ----- |
218 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | `apierr.ErrorCode() == anthropic.ErrorCodeEnforcedSpendLimitReached` |
219 | One HTTP status | `apierr.StatusCode == http.StatusTooManyRequests` |
220 | Every error response | `errors.As(err, &apierr)` |
221 | An error event in a stream | `errors.As(stream.Err(), &apierr)` |
222 | A connection failure, a client timeout, or a connection that drops in mid-stream | Any other `err` that isn’t `nil` |
223 
224 Each error code has its own constant (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)).
225 
226 To print the raw request and response of a `*anthropic.Error`, see [Error handling in Go](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go#error-handling).
227 </Tab>
228 
229 <Tab title="Java">
230 These classes are in the `com.anthropic.errors` package unless a row names another. A class also catches its subclasses, so put the narrower class first. For example, `RateLimitException` also catches `EnforcedSpendLimitReachedException`.
231 
232 | To handle | Catch |
233 | ----- | ----- |
234 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | Its own class, such as `com.anthropic.models.EnforcedSpendLimitReachedException` (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)) |
235 | 400 | `BadRequestException` |
236 | 401 | `UnauthorizedException` |
237 | 403 | `PermissionDeniedException` |
238 | 404 | `NotFoundException` |
239 | 409 | `ConflictException` |
240 | 413 | `ContentTooLargeException` |
241 | 422 | `UnprocessableEntityException` |
242 | 429 | `RateLimitException` |
243 | 504 | `GatewayTimeoutException` |
244 | 529 | `OverloadedException` |
245 | Every 5xx, such as 500, 504, and 529 | `InternalServerException` |
246 | An error event in a stream | `SseException` |
247 | Every error response and every error event in a stream | `AnthropicServiceException` |
248 | A connection failure, a client timeout, or a connection that drops in mid-stream | `AnthropicIoException` |
249 | Every error in this table | `AnthropicException` |
250 
251 For a status that has no row, such as 402, catch `AnthropicServiceException` and compare its `statusCode()`.
252 
253 The error’s `errorCode()` and `type()` each return an `Optional`.
254 
255 To read the response headers, see [Error handling in Java](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#error-handling).
256 </Tab>
257 
258 <Tab title="PHP">
259 These classes are in the `Anthropic\Core\Exceptions` namespace unless a row names another. A class also catches its subclasses, so put the narrower class first. For example, `RateLimitException` also catches `EnforcedSpendLimitReachedException`.
260 
261 | To handle | Catch |
262 | ----- | ----- |
263 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | Its own class, such as `Anthropic\EnforcedSpendLimitReachedException` (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)) |
264 | 400 | `BadRequestException` |
265 | 401 | `AuthenticationException` |
266 | 403 | `PermissionDeniedException` |
267 | 404 | `NotFoundException` |
268 | 409 | `ConflictException` |
269 | 413 | `ContentTooLargeException` |
270 | 422 | `UnprocessableEntityException` |
271 | 429 | `RateLimitException` |
272 | 504 | `GatewayTimeoutException` |
273 | 529 | `OverloadedException` |
274 | Every 5xx, such as 500, 504, and 529 | `InternalServerException` |
275 | Every error response | `APIStatusException` |
276 | An error event in a stream | `APIStatusException` |
277 | A connection failure before a response arrives or a client timeout | `APIConnectionException` |
278 | A connection that drops in mid-stream | The HTTP client’s own exception or none (see the paragraph after this table). With Guzzle 7, a connection reset raises PHP’s `\RuntimeException`. |
279 | Every error in this table except a dropped stream | `APIException` |
280 
281 If the server closes the connection in mid-stream, the stream ends with no error. Check that a `message_stop` event arrived.
282 
283 For a status that has no row, such as 402, catch `APIStatusException` and compare its `status`.
284 
285 To reach the underlying exception, see [Error handling in PHP](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/php#error-handling).
286 </Tab>
287 
288 <Tab title="Ruby">
289 These classes are in the `Anthropic::Errors` module unless a row names another. A class also catches its subclasses, so put the narrower class first. For example, `RateLimitError` also catches `EnforcedSpendLimitReachedError`.
290 
291 | To handle | Catch |
292 | ----- | ----- |
293 | One [error code](https://platform.claude.com/docs/en/api/errors#error-codes) | Its own class, such as `Anthropic::EnforcedSpendLimitReachedError` (see [Handle a specific error code](https://platform.claude.com/docs/en/api/handle-errors#handle-a-specific-error-code)) |
294 | 400 | `BadRequestError` |
295 | 401 | `AuthenticationError` |
296 | 403 | `PermissionDeniedError` |
297 | 404 | `NotFoundError` |
298 | 409 | `ConflictError` |
299 | 413 | `ContentTooLargeError` |
300 | 422 | `UnprocessableEntityError` |
301 | 429 | `RateLimitError` |
302 | 504 | `GatewayTimeoutError` |
303 | 529 | `OverloadedError` |
304 | Every 5xx, such as 500, 504, and 529 | `InternalServerError` |
305 | Every error response | `APIStatusError` |
306 | An error event in a stream | `APIStatusError` |
307 | A client timeout (the SDK stopped waiting) | `APITimeoutError` |
308 | Every connection failure (including a client timeout and a connection that drops in mid-stream) | `APIConnectionError` |
309 | Every error in this table | `APIError` |
310 
311 For a status that has no row, such as 402, catch `APIStatusError` and compare its `status`.
312 
313 The error’s `error_code` and `type` are symbols.
314 
315 To reach the underlying exception, see [Handling errors in Ruby](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/ruby#handling-errors).
316 </Tab>
317</Tabs>
318 
319The table goes by HTTP status and error code, not by `error.type`:
320 
321* A 503 with `overloaded_error` counts as a 5xx, not as a 529.
322* An error event in a stream never matches a status row or a code’s class. Its HTTP status is the stream’s 200 or is missing.
323 
324To go by `error.type` instead, check the error’s `type` (csharp: `Type`; go: `Type()`; java: `type()`; php: `getType()`) as in [Handle an error in a stream](https://platform.claude.com/docs/en/api/handle-errors#handle-an-error-in-a-stream).
325 
87326## Request ID
88327 
89328Every API response includes a unique `request-id` header. This header contains a value such as `req_018EeWyXxfu5pfWkrYcMdjWG`. The same identifier appears as the `request_id` field in [error response bodies](https://platform.claude.com/docs/en/api/errors#error-shapes). When contacting support about a specific request, include this ID to help quickly resolve your issue.
from line 329
90329 
91330On [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws), responses include two request IDs: the AWS request ID (`x-amzn-requestid`, primary, indexed in CloudTrail) and the Anthropic request ID (`request-id`, secondary). Use the AWS request ID for CloudTrail lookups and the Anthropic request ID for Anthropic support tickets.
92331 
332When the API returns an error response, read the ID from the SDK error in `request_id` (typescript: `requestID`; csharp, go: `RequestID`; java: `requestId()`; php: `getRequestID()`). For a sample, see [Catch errors by kind](https://platform.claude.com/docs/en/api/handle-errors#catch-errors-by-kind). When a request succeeds, read the ID from the response.
333 
93334The Python and TypeScript SDKs expose the request ID as a `_request_id` property on top-level response objects. The C#, Go, Java, and PHP SDKs expose it through their raw-response accessors, and the Ruby SDK through [middleware](https://platform.claude.com/docs/en/cli-sdks-libraries/middleware). In every SDK except Ruby, use `with_raw_response` (typescript: `.withResponse()`; java: `.withRawResponse()`; csharp: `WithRawResponse`; go: `option.WithResponseInto()`; php: `->raw`) to read any other [response header](https://platform.claude.com/docs/en/api/overview#response-headers), such as `anthropic-organization-id` and [`anthropic-workspace-id`](https://platform.claude.com/docs/en/manage-claude/workspaces#identify-the-workspace-behind-an-api-response). In Ruby, use the same middleware. On Claude Platform on AWS, use the raw-response accessor to read the AWS request ID (`x-amzn-requestid`) as well:
94335 
95336<CodeGroup>
from line 827
586827 To mitigate misuse and manage capacity on the API, limits are in place on how much an organization can use the Claude API.
587828 </Card>
588829 
589 <Card title="Streaming messages" icon="lightning" href="https://platform.claude.com/docs/en/build-with-claude/streaming">
590 Stream Messages API responses incrementally with server-sent events, including text, tool use, and extended thinking deltas.
830 <Card title="Handle errors" icon="code" href="https://platform.claude.com/docs/en/api/handle-errors">
831 Use the SDK to catch Claude API errors by error code, HTTP status, or connection failure and to handle an error that arrives in a stream.
591832 </Card>
592833</CardGroup>
593834 

api/handle-errors New page · 495 lines, new page

## Catch errors by kind ## Handle a specific error code ## Handle an error in a stream

A whole new page. There's nothing to diff it against, so here is what it says.

---
title: Handle errors
url: https://platform.claude.com/docs/en/api/handle-errors
description: Use the SDK to catch Claude API errors by error code, HTTP status, or connection failure and to handle an error that arrives in a stream.
---

Use the SDK to catch Claude API errors by error code, HTTP status, or connection failure and to handle an error that arrives in a stream. To learn what each error means or to call the API without the SDK, see [Claude API errors](https://platform.claude.com/docs/en/api/errors).

<Note>
  The examples on this page need the [latest version of the SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview#latest-versions).
</Note>

## Catch errors by kind

This example handles one [error code](https://platform.claude.com/docs/en/api/errors#error-codes), one HTTP status, a connection failure, and every other error response:

<CodeGroup exclude="shell:cURL, shell:CLI">
  ```python Python
  client = anthropic.Anthropic()

  try:
      client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          messages=[{"role": "user", "content": "Hello, Claude"}],
      )
  except anthropic.EnforcedSpendLimitReachedError as e:
      # One error code: enforced_spend_limit_reached
      print("Monthly spend cap reached:", e.api_message)
  except anthropic.RateLimitError as e:
      # One HTTP status: any other 429
      print("Rate limited. Request ID:", e.request_id)
  except anthropic.APIConnectionError:
      # An error with no response, such as a network failure or a timeout
      print("Connection failed")
  except anthropic.APIStatusError as e:
      # Every other error response
      print(e.status_code)  # HTTP status
      print(e.type)  # error.type
      print(e.api_message)  # error.message
      print(e.error_code)  # error.details.error_code if any
      print(e.details)  # error.details if any
      print(e.request_id)  # request_id
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  try {
    await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello, Claude" }]
    });
  } catch (err) {
    if (err instanceof Anthropic.EnforcedSpendLimitReachedError) {
      // One error code: enforced_spend_limit_reached
      console.log("Monthly spend cap reached:", err.apiMessage);
    } else if (err instanceof Anthropic.RateLimitError) {
      // One HTTP status: any other 429
      console.log("Rate limited. Request ID:", err.requestID);
    } else if (err instanceof Anthropic.APIConnectionError) {
      // An error with no response, such as a network failure or a timeout
      console.log("Connection failed");
    } else if (err instanceof Anthropic.APIError) {
      // Every other error response
      console.log(err.status); // HTTP status
      console.log(err.type); // error.type
      console.log(err.apiMessage); // error.message
      console.log(err.errorCode); // error.details.error_code if any
      console.log(err.details); // error.details if any
      console.log(err.requestID); // request_id
    } else {
      throw err;
    }
  }
  ```

  ```csharp C#
  using Anthropic.Exceptions;
  using Anthropic.Models;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  try
  {
      await client.Messages.Create(new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Messages = [new UserMessageParam { Content = "Hello, Claude" }]
      });
  }
  catch (AnthropicEnforcedSpendLimitReachedException e)
  {
      // One error code: enforced_spend_limit_reached
      Console.WriteLine($"Monthly spend cap reached: {e.ApiMessage}");
  }
  catch (AnthropicRateLimitException e)
  {
      // One HTTP status: any other 429
      Console.WriteLine($"Rate limited. Request ID: {e.RequestID}");
  }
  catch (Exception e) when (e is AnthropicIOException or TaskCanceledException)
  {
      // An error with no response, such as a network failure or a timeout
      Console.WriteLine("Connection failed");
  }
  catch (AnthropicApiException e)
  {
      // Every other error response
      Console.WriteLine((int)e.StatusCode); // HTTP status
      Console.WriteLine(e.Type?.Raw()); // error.type
      Console.WriteLine(e.ApiMessage); // error.message
      Console.WriteLine(e.ErrorCode); // error.details.error_code if any
      Console.WriteLine(e.Details); // error.details if any
      Console.WriteLine(e.RequestID); // request_id
  }
  ```

  ```go Go
  client := anthropic.NewClient()

  _, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
  	},
  })

  // The Go SDK has one error type. Branch on the error's code and status.
  var apierr *anthropic.Error
  if errors.As(err, &apierr) {
  	switch {
  	case apierr.ErrorCode() == anthropic.ErrorCodeEnforcedSpendLimitReached:
  		// One error code: enforced_spend_limit_reached
  		fmt.Println("Monthly spend cap reached:", apierr.Message)
  	case apierr.StatusCode == http.StatusTooManyRequests:
  		// One HTTP status: any other 429
  		fmt.Println("Rate limited. Request ID:", apierr.RequestID)
  	default:
  		// Every other error response
  		fmt.Println(apierr.StatusCode)        // HTTP status
  		fmt.Println(apierr.Type())            // error.type
  		fmt.Println(apierr.Message)           // error.message
  		fmt.Println(apierr.ErrorCode())       // error.details.error_code if any
  		fmt.Println(apierr.Details.RawJSON()) // error.details if any
  		fmt.Println(apierr.RequestID)         // request_id
  	}
  } else if err != nil {
  	// Any other error, such as a network failure or a timeout
  	fmt.Println("Connection failed")
  }
  ```

  ```java Java
  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.errors.AnthropicIoException;
  import com.anthropic.errors.AnthropicServiceException;
  import com.anthropic.errors.RateLimitException;
  import com.anthropic.models.EnforcedSpendLimitReachedException;
  import com.anthropic.models.messages.MessageCreateParams;
  import com.anthropic.models.messages.Model;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addUserMessage("Hello, Claude")
          .build();

      try {
          client.messages().create(params);
      } catch (EnforcedSpendLimitReachedException e) {
          // One error code: enforced_spend_limit_reached
          IO.println("Monthly spend cap reached: " + e.apiMessage().orElse(""));
      } catch (RateLimitException e) {
          // One HTTP status: any other 429
          IO.println("Rate limited. Request ID: " + e.requestId().orElse(""));
      } catch (AnthropicIoException e) {
          // An error with no response, such as a network failure or a timeout
          IO.println("Connection failed");
      } catch (AnthropicServiceException e) {
          // Every other error response
          IO.println(e.statusCode()); // HTTP status
          IO.println(e.type().orElse(null)); // error.type
          IO.println(e.apiMessage().orElse(null)); // error.message
          IO.println(e.errorCode().orElse(null)); // error.details.error_code if any
          IO.println(e.errorDetails().orElse(null)); // error.details if any
          IO.println(e.requestId().orElse(null)); // request_id
      }
  }
  ```

  ```php PHP
  use Anthropic\Core\Exceptions\APIConnectionException;
  use Anthropic\Core\Exceptions\APIStatusException;
  use Anthropic\Core\Exceptions\RateLimitException;
  use Anthropic\EnforcedSpendLimitReachedException;
  use Anthropic\Messages\Model;

  $client = new Client();

  try {
      $client->messages->create(
          model: Model::CLAUDE_OPUS_5_5,
          maxTokens: 1024,
          messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      );
  } catch (EnforcedSpendLimitReachedException $e) {
      // One error code: enforced_spend_limit_reached
      echo 'Monthly spend cap reached: ', $e->getAPIMessage(), PHP_EOL;
  } catch (RateLimitException $e) {
      // One HTTP status: any other 429
      echo 'Rate limited. Request ID: ', $e->getRequestID(), PHP_EOL;
  } catch (APIConnectionException) {
      // An error with no response, such as a network failure or a timeout
      echo 'Connection failed', PHP_EOL;
  } catch (APIStatusException $e) {
      // Every other error response
      echo $e->status, PHP_EOL; // HTTP status
      echo $e->getType(), PHP_EOL; // error.type
      echo $e->getAPIMessage(), PHP_EOL; // error.message
      echo $e->getErrorCode(), PHP_EOL; // error.details.error_code if any
      echo json_encode($e->getDetails()), PHP_EOL; // error.details if any
      echo $e->getRequestID(), PHP_EOL; // request_id
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  begin
    client.messages.create(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello, Claude" }]
    )
  rescue Anthropic::EnforcedSpendLimitReachedError => e
    # One error code: enforced_spend_limit_reached
    puts "Monthly spend cap reached: #{e.api_message}"
  rescue Anthropic::Errors::RateLimitError => e
    # One HTTP status: any other 429
    puts "Rate limited. Request ID: #{e.request_id}"
  rescue Anthropic::Errors::APIConnectionError
    # An error with no response, such as a network failure or a timeout
    puts "Connection failed"
  rescue Anthropic::Errors::APIStatusError => e
    # Every other error response
    puts e.status # HTTP status
    puts e.type # error.type as a symbol
    puts e.api_message # error.message
    puts e.error_code # error.details.error_code as a symbol if any
    puts e.details # error.details if any
    puts e.request_id # request_id
  end
  ```
</CodeGroup>

An error reaches your code after the SDK’s own retries, if any, have failed (see [Retries](https://platform.claude.com/docs/en/api/errors#retries)). For what each status means, see [HTTP errors](https://platform.claude.com/docs/en/api/errors#http-errors).

Keep a narrow case before a broad one. The Messages API returns `enforced_spend_limit_reached`, the code for the [monthly spend cap](https://platform.claude.com/docs/en/api/rate-limits#reaching-your-spend-cap), with a 429. If the branch for a 429 came first, it would catch that code too.

To handle another case, such as a 404, see [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types).

## Handle a specific error code

To handle another error code, add its branch to [Catch errors by kind](https://platform.claude.com/docs/en/api/handle-errors#catch-errors-by-kind) before any broader branch.

Each code has its own class or constant named after the code, such as `anthropic.EnforcedSpendLimitReachedError` (typescript: `Anthropic.EnforcedSpendLimitReachedError`; ruby: `Anthropic::EnforcedSpendLimitReachedError`; java: `com.anthropic.models.EnforcedSpendLimitReachedException`; php: `Anthropic\EnforcedSpendLimitReachedException`; csharp: `Anthropic.Models.AnthropicEnforcedSpendLimitReachedException`; go: `anthropic.ErrorCodeEnforcedSpendLimitReached`). Classes for other codes might sit in other namespaces. To find one, search the SDK’s source for the class name. A method’s doc comment lists the class or constant for each code that the method can return.

For the full list of codes, see [`ErrorDetails`](https://platform.claude.com/docs/en/api/$shared#error_details) in the API reference.

## Handle an error in a stream

After a stream starts, the API has already returned a 200, so it sends an error as an [error event](https://platform.claude.com/docs/en/build-with-claude/streaming#error-events). The SDK doesn’t retry the request.

Every error event reaches you as `APIStatusError` (typescript: `APIError`; csharp: `AnthropicSseException`; java: `SseException`; php: `APIStatusException`; go: `*anthropic.Error`). Its HTTP status is the stream’s 200 or is missing. So a branch for one status or for one code’s class doesn’t catch it. Instead, check its `error.type` for one of the types in [HTTP errors](https://platform.claude.com/docs/en/api/errors#http-errors):

<CodeGroup exclude="shell:cURL, shell:CLI">
  ```python Python
  client = anthropic.Anthropic()

  try:
      with client.messages.stream(
          model="claude-opus-5-5",
          max_tokens=1024,
          messages=[{"role": "user", "content": "Hello, Claude"}],
      ) as stream:
          for text in stream.text_stream:
              print(text, end="", flush=True)
  except anthropic.APIStatusError as e:
      if e.type == "overloaded_error":
          # One error.type: overloaded_error
          print("\nOverloaded:", e.api_message)

Cut at 300 lines. The page has the rest.

build-with-claude/streaming Changed · +2 / -4 lines

from line 347
347347data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
348348```
349349 
350If you use the SDK, your code doesn’t receive this event. The SDK ends the stream, and the code that reads the stream gets an error instead. To handle it, see [Handle an error in a stream](https://platform.claude.com/docs/en/api/handle-errors#handle-an-error-in-a-stream).
351 
350352### Other events
351353 
352354In accordance with the [versioning policy](https://platform.claude.com/docs/en/api/versioning), new event types may be added, and your code should handle unknown event types gracefully.
from line 1554
15521554 
15531555 <Card title="Thinking" icon="brain" href="https://platform.claude.com/docs/en/build-with-claude/thinking">
15541556 Stream thinking output with `thinking_delta` and `signature_delta` events.
1555 </Card>
1556 
1557 <Card title="Client SDKs" icon="code" href="https://platform.claude.com/docs/en/cli-sdks-libraries/overview">
1558 Use the official SDKs, which handle streaming, accumulation, and reconnection for you.
15591557 </Card>
15601558 
15611559 <Card title="Batch processing" icon="stack" href="https://platform.claude.com/docs/en/build-with-claude/batch-processing">

cli-sdks-libraries/sdks/csharp Changed · +10 / -33 lines

from line 138
138138 
139139## Error handling
140140 
141The SDK throws custom unchecked exception types:
141The SDK throws `AnthropicApiException` when the API returns an error response and `AnthropicIOException` when the SDK can’t connect to the API. These and the SDK’s other exceptions extend `AnthropicException`. [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types) lists the cases (including errors in a stream), and [Handle errors](https://platform.claude.com/docs/en/api/handle-errors) shows how to catch these exceptions.
142142 
143* `AnthropicApiException`: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:
144 
145| Status | Exception |
146| ----- | ----- |
147| 400 | `AnthropicBadRequestException` |
148| 401 | `AnthropicUnauthorizedException` |
149| 403 | `AnthropicForbiddenException` |
150| 404 | `AnthropicNotFoundException` |
151| 422 | `AnthropicUnprocessableEntityException` |
152| 429 | `AnthropicRateLimitException` |
153| 5xx | `Anthropic5xxException` |
154| others | `AnthropicUnexpectedStatusCodeException` |
155 
156Additionally, all 4xx errors inherit from `Anthropic4xxException`.
157 
158* `AnthropicSseException`: Errors encountered during SSE streaming after a successful initial HTTP response.
159 
160* `AnthropicIOException`: I/O networking errors.
161 
162* `AnthropicInvalidDataException`: Failure to interpret successfully parsed data. For example, when accessing a property that’s supposed to be required, but the API unexpectedly omitted it from the response.
163 
164* `AnthropicException`: Base class for all exceptions.
165 
166143## Retries
167144 
168The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
145By default, the SDK retries certain errors up to two times (three attempts in all).
169146 
170Only the following error types are retried:
147The SDK retries the following error types:
171148 
172* Connection errors (for example, because of a network connectivity problem)
149* Connection errors and timeouts
173150* 408 Request Timeout
174151* 409 Conflict
175* 429 Rate Limit
176* 5xx Internal
152* 429 Too Many Requests
153* 5xx server errors
177154 
178The API might also explicitly instruct the SDK to retry or not retry a request.
155If a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
179156 
180157To set a custom number of retries, configure the client using the `MaxRetries` property:
181158 

cli-sdks-libraries/sdks/go Changed · +20 / -3 lines

### Retries for create methods

from line 474
474474}
475475```
476476 
477To branch on the error code and the HTTP status, see [Handle errors](https://platform.claude.com/docs/en/api/handle-errors).
478 
477479When other errors occur, they are returned unwrapped; for example, if HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`.
478480 
479481## Retries
480482 
481Certain errors are automatically retried 2 times by default, with a short exponential backoff. The SDK retries by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.
483By default, the SDK retries certain errors up to two times (three attempts in all). It retries [some create methods](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go#retries-for-create-methods) in fewer cases.
482484 
483You can use the `WithMaxRetries` option to configure or disable this:
485For most methods, such as `client.Messages.New()`, the SDK retries connection errors, timeouts, 408 Request Timeout, 409 Conflict, 429 Too Many Requests, and 5xx server errors.
484486 
487For these methods, if a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
488 
489Use `option.WithMaxRetries()` to configure or disable retries:
490 
485491```go
486492// Configure the default for all requests:
487493client := anthropic.NewClient(
from line 508
502508 option.WithMaxRetries(5),
503509 )
504510```
511 
512### Retries for create methods
513 
514To avoid duplicate resources, the SDK retries some create methods, such as `client.Beta.Agents.New()`, in only two cases:
515 
516* The API returns a 429 Too Many Requests response.
517* The SDK can’t connect to the API, so it never sends the request.
518 
519In both cases, the API hasn’t processed the request, so a retry can’t create a second resource.
520 
521These methods return any other error without a retry even if the response has `x-should-retry: true`. The API might have created the resource if a server error occurred or if the connection dropped or timed out after the SDK sent the request. Check whether the resource exists before you call the method again.
505522 
506523## Timeouts
507524 

cli-sdks-libraries/sdks/java Changed · +12 / -47 lines

### Status code mapping

from line 596
596596 
597597## Error handling
598598 
599The SDK throws custom unchecked exception types:
599The SDK throws a subclass of `AnthropicException` when a request fails. Causes include a connection failure and an error response from the API. These exceptions are unchecked. [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types) lists the cases (including errors in a stream), and [Handle errors](https://platform.claude.com/docs/en/api/handle-errors) shows how to catch these exceptions.
600600 
601* `AnthropicServiceException` - Base class for HTTP errors
602* `AnthropicIoException` - I/O networking errors
603* `AnthropicRetryableException` - Generic error indicating a failure that could be retried
604* `AnthropicInvalidDataException` - Failure to interpret successfully parsed data (for example, when accessing a property that’s supposed to be required, but the API unexpectedly omitted it)
605* `AnthropicException` - Base class for all exceptions
601Each exception for an error response extends `AnthropicServiceException`. To read the response’s headers, catch that class and call `headers()`. For example, `e.headers().values("retry-after")` returns that header’s values as a list.
606602 
607### Status code mapping
608 
609| Status | Exception |
610| ----- | ----- |
611| 400 | `BadRequestException` |
612| 401 | `UnauthorizedException` |
613| 403 | `PermissionDeniedException` |
614| 404 | `NotFoundException` |
615| 422 | `UnprocessableEntityException` |
616| 429 | `RateLimitException` |
617| 5xx | `InternalServerException` |
618| others | `UnexpectedStatusCodeException` |
619 
620`SseException` is thrown for errors encountered during SSE streaming after a successful initial HTTP response.
621 
622```java
623import com.anthropic.errors.*;
624 
625try {
626 Message message = client.messages().create(params);
627} catch (RateLimitException e) {
628 IO.println("Rate limited, retry after: " + e.headers());
629} catch (UnauthorizedException e) {
630 IO.println("Invalid API key");
631} catch (AnthropicServiceException e) {
632 IO.println("API error: " + e.statusCode());
633} catch (AnthropicIoException e) {
634 IO.println("Network error: " + e.getMessage());
635}
636```
637 
638603## Request IDs
639604 
640605When using [raw responses](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#raw-response-access), you can access the `request-id` response header using the `requestId()` method:
from line 617
652617 
653618## Retries
654619 
655The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
620By default, the SDK retries certain errors up to two times (three attempts in all).
656621 
657Only the following error types are retried:
622The SDK retries the following error types:
658623 
659* Connection errors (for example, because of a network connectivity problem)
624* Connection errors and timeouts
660625* 408 Request Timeout
661626* 409 Conflict
662* 429 Rate Limit
663* 5xx Internal
627* 429 Too Many Requests
628* 5xx server errors
664629 
665The API might also explicitly instruct the SDK to retry or not retry a request.
630If a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
666631 
667632To set a custom number of retries, configure the client using the `maxRetries` method:
668633 

cli-sdks-libraries/sdks/php Changed · +8 / -47 lines

from line 75
7575 
7676## Error handling
7777 
78When the library is unable to connect to the API, or if the API returns a non-success status code (that is, a 4xx or 5xx response), a subclass of `Anthropic\Core\Exceptions\APIException` is thrown:
78The SDK throws a subclass of `Anthropic\Core\Exceptions\APIException` when it can’t connect to the API or when the API returns an error response (4xx or 5xx). [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types) lists the classes, and [Handle errors](https://platform.claude.com/docs/en/api/handle-errors) shows how to catch them.
7979 
80```php
81<?php
82// ...
83use Anthropic\Core\Exceptions\APIConnectionException;
84use Anthropic\Core\Exceptions\APIStatusException;
85use Anthropic\Core\Exceptions\RateLimitException;
86use Anthropic\Messages\Model;
87// ...
88try {
89 $message = $client->messages->create(
90 maxTokens: 1024,
91 messages: [['role' => 'user', 'content' => 'Hello, Claude']],
92 model: Model::CLAUDE_OPUS_5_5,
93 );
94} catch (APIConnectionException $e) {
95 echo 'The server could not be reached', PHP_EOL;
96 echo $e->getPrevious()?->getMessage(), PHP_EOL;
97} catch (RateLimitException $_) {
98 echo 'A 429 status code was received; we should back off a bit.', PHP_EOL;
99} catch (APIStatusException $e) {
100 echo 'Another non-200-range status code was received', PHP_EOL;
101 echo $e->getMessage();
102}
103```
80To see why a connection failed or timed out, call `getPrevious()` on the `Anthropic\Core\Exceptions\APIConnectionException`. The method returns the underlying exception or `null` if there isn’t one.
10481 
105Error codes are as follows:
106 
107| Cause | Error type |
108| ----- | ----- |
109| HTTP 400 | `BadRequestException` |
110| HTTP 401 | `AuthenticationException` |
111| HTTP 403 | `PermissionDeniedException` |
112| HTTP 404 | `NotFoundException` |
113| HTTP 409 | `ConflictException` |
114| HTTP 422 | `UnprocessableEntityException` |
115| HTTP 429 | `RateLimitException` |
116| HTTP >= 500 | `InternalServerException` |
117| Other HTTP error | `APIStatusException` |
118| Timeout | `APITimeoutException` |
119| Network error | `APIConnectionException` |
120 
12182## Retries
12283 
123Certain errors are automatically retried two times by default, with a short exponential backoff.
84By default, the SDK retries certain errors up to two times (three attempts in all). It retries connection errors, timeouts, 408 Request Timeout, 409 Conflict, 429 Too Many Requests, and 5xx server errors.
12485 
125Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts are all retried by default.
86If a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
12687 
127You can use the `maxRetries` option to configure or disable this:
88Use the `maxRetries` request option to configure or disable retries:
12889 
12990```php
13091use Anthropic\Messages\Model;

cli-sdks-libraries/sdks/python Changed · +13 / -43 lines

from line 349
349349 
350350## Handling errors
351351 
352The SDK raises a subclass of `APIError` when it can’t connect to the API or when the API returns a 4xx or 5xx status code:
352The SDK raises a subclass of `anthropic.APIError` when it can’t connect to the API or when the API returns an error response (4xx or 5xx). [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types) lists the classes, and [Handle errors](https://platform.claude.com/docs/en/api/handle-errors) shows how to catch them.
353353 
354```python
355import anthropic
356# ...
357try:
358 message = client.messages.create(
359 max_tokens=1024,
360 messages=[
361 {
362 "role": "user",
363 "content": "Hello, Claude",
364 }
365 ],
366 model="claude-opus-5-5",
367 )
368except anthropic.APIConnectionError as e:
369 print("The server could not be reached")
370 print(e.__cause__) # an underlying Exception, likely raised within httpx2
371except anthropic.RateLimitError as e:
372 print("A 429 status code was received; wait before retrying.")
373except anthropic.APIStatusError as e:
374 print("Another non-200-range status code was received")
375 print(e.status_code)
376 print(e.response)
377```
354Two of the classes hold more detail on a failure:
378355 
379Error codes are as follows:
356| Class | Raised when | Where the detail is |
357| ----- | ----- | ----- |
358| `APIConnectionError` | The SDK can’t reach the API, or the request times out (the subclass `APITimeoutError`) | `__cause__` holds the underlying exception |
359| `APIStatusError` | The API returns an error response | `status_code` holds the status, and `response` holds the raw `httpx2.Response` with its headers |
380360 
381| Status code | Error type |
382| ----- | ----- |
383| 400 | `BadRequestError` |
384| 401 | `AuthenticationError` |
385| 403 | `PermissionDeniedError` |
386| 404 | `NotFoundError` |
387| 409 | `ConflictError` |
388| 422 | `UnprocessableEntityError` |
389| 429 | `RateLimitError` |
390| >=500 | `InternalServerError` |
391| N/A | `APIConnectionError` |
392 
393361## Request IDs
394362 
395363> For more information on debugging requests, see [Request ID](https://platform.claude.com/docs/en/api/errors#request-id).
from line 379
411379 
412380## Retries
413381 
414By default, the SDK retries certain errors twice, with a short exponential backoff. It retries connection errors (for example, a network problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.
382By default, the SDK retries certain errors up to two times (three attempts in all). It retries connection errors, timeouts, 408 Request Timeout, 409 Conflict, 429 Too Many Requests, and 5xx server errors.
415383 
416You can use the `max_retries` option to configure or disable this:
384If a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
385 
386Use the `max_retries` option to configure or disable retries:
417387 
418388```python
419389# Configure the default for all requests:

cli-sdks-libraries/sdks/ruby Changed · +8 / -41 lines

from line 113
113113 
114114## Handling errors
115115 
116When the library is unable to connect to the API, or if the API returns a non-success status code (that is, a 4xx or 5xx response), a subclass of `Anthropic::Errors::APIError` is raised:
116The SDK raises a subclass of `Anthropic::Errors::APIError` when it can’t connect to the API or when the API returns an error response (4xx or 5xx). [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types) lists the classes, and [Handle errors](https://platform.claude.com/docs/en/api/handle-errors) shows how to rescue them.
117117 
118```ruby
119anthropic = Anthropic::Client.new
120begin
121 message = anthropic.messages.create(
122 max_tokens: 1024,
123 messages: [{role: "user", content: "Hello, Claude"}],
124 model: Anthropic::Model::CLAUDE_OPUS_5_5
125 )
126rescue Anthropic::Errors::APIConnectionError => e
127 puts("The server could not be reached")
128 puts(e.cause) # an underlying Exception, likely raised within `net/http`
129rescue Anthropic::Errors::RateLimitError => e
130 puts("A 429 status code was received; we should back off a bit.")
131rescue Anthropic::Errors::APIStatusError => e
132 puts("Another non-200-range status code was received")
133 puts(e.status)
134end
135```
118To see why a connection failed or timed out, read `cause` on the `Anthropic::Errors::APIConnectionError` or its subclass `APITimeoutError`. `cause` holds the underlying exception.
136119 
137Error codes are as follows:
138 
139| Cause | Error type |
140| ----- | ----- |
141| HTTP 400 | `BadRequestError` |
142| HTTP 401 | `AuthenticationError` |
143| HTTP 403 | `PermissionDeniedError` |
144| HTTP 404 | `NotFoundError` |
145| HTTP 409 | `ConflictError` |
146| HTTP 422 | `UnprocessableEntityError` |
147| HTTP 429 | `RateLimitError` |
148| HTTP >= 500 | `InternalServerError` |
149| Other HTTP error | `APIStatusError` |
150| Timeout | `APITimeoutError` |
151| Network error | `APIConnectionError` |
152 
153120## Retries
154121 
155Certain errors are automatically retried 2 times by default, with a short exponential backoff.
122By default, the SDK retries certain errors up to two times (three attempts in all). It retries connection errors, timeouts, 408 Request Timeout, 409 Conflict, 429 Too Many Requests, and 5xx server errors.
156123 
157Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts are all retried by default.
124If a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
158125 
159You can use the `max_retries` option to configure or disable this:
126Use the `max_retries` option to configure or disable retries:
160127 
161128```ruby
162129# Configure the default for all requests:

cli-sdks-libraries/sdks/typescript Changed · +13 / -36 lines

from line 374
374374 
375375## Handling errors
376376 
377When the library is unable to connect to the API, or if the API returns a non-success status code (that is, a 4xx or 5xx response), a subclass of `APIError` is thrown:
377The SDK throws a subclass of `Anthropic.APIError` when it can’t connect to the API or when the API returns an error response (4xx or 5xx). [SDK error types](https://platform.claude.com/docs/en/api/errors#sdk-error-types) lists the classes, and [Handle errors](https://platform.claude.com/docs/en/api/handle-errors) shows how to catch them.
378378 
379```typescript
380const message = await client.messages
381 .create({
382 max_tokens: 1024,
383 messages: [{ role: "user", content: "Hello, Claude" }],
384 model: "claude-opus-5-5"
385 })
386 .catch(async (err) => {
387 if (err instanceof Anthropic.APIError) {
388 console.log(err.status); // 400
389 console.log(err.name); // BadRequestError
390 console.log(err.headers); // {server: 'nginx', ...}
391 } else {
392 throw err;
393 }
394 });
395```
379The error’s `status` and `headers` properties hold the response’s status and headers (for example, `err.headers?.get("retry-after")`). Both are `undefined` if there was no response.
396380 
397Error codes are as follows:
381Two errors don’t come from a failed connection or an error response. A check for `APIError` matches the first but not the second:
398382 
399| Status code | Error type |
400| ----- | ----- |
401| 400 | `BadRequestError` |
402| 401 | `AuthenticationError` |
403| 403 | `PermissionDeniedError` |
404| 404 | `NotFoundError` |
405| 409 | `ConflictError` |
406| 422 | `UnprocessableEntityError` |
407| 429 | `RateLimitError` |
408| >=500 | `InternalServerError` |
409| N/A | `APIConnectionError` |
383* **`APIUserAbortError`:** You aborted a request with the `signal` request option (an `AbortSignal`) or called `abort()` on a [`client.messages.stream()` stream](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript#streaming-helpers).
384* **`AnthropicError`:** The SDK itself failed. For example, it refused a long non-streaming request (see [Long requests](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript#long-requests)). `AnthropicError` is the parent class of `APIError`.
410385 
411386## Request IDs
412387 
from line 400
425400 
426401## Retries
427402 
428Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.
403By default, the SDK retries certain errors up to two times (three attempts in all). It retries connection errors, timeouts, 408 Request Timeout, 409 Conflict, 429 Too Many Requests, and 5xx server errors.
429404 
430You can use the `maxRetries` option to configure or disable this:
405If a response has an `x-should-retry` header (`true` or `false`), the SDK follows it instead of the status. Between attempts, the SDK waits as long as the `retry-after` header says, or it uses a short exponential backoff.
406 
407Use the `maxRetries` option to configure or disable retries:
431408 
432409```typescript
433410// Configure the default for all requests:

release-notes/overview Changed · +4 / -0 lines

### November 4, 2026

from line 85
8585* You can now set up an IP allowlist for your organization in the Claude Console, in beta. Requests to covered services from addresses not on your list are refused, which limits where a leaked API key can be used. Add IPv4 and IPv6 addresses or CIDR ranges, up to 1,000 per organization. See [IP allowlisting](https://platform.claude.com/docs/en/manage-claude/ip-allowlist) for what’s covered and how to set it up.
8686* You can now sign a member of your Claude Enterprise (claude.ai) organization out of Claude everywhere with the Admin API. This capability is in beta. See the [Admin API reference](https://platform.claude.com/docs/en/api/beta/organization). The member stays in the organization and can sign in again. See [Sign a member out everywhere](https://platform.claude.com/docs/en/manage-claude/user-management#sign-a-member-out-everywhere) for the beta header and what the request doesn’t end.
8787 
88### November 4, 2026
89 
90* We’ve added [error codes](https://platform.claude.com/docs/en/api/errors#error-codes) to the SDK so you can handle one cause of an error without parsing the response body. Each API error now carries the API’s error code, message, and details, and each error code has its own exception class (in Go, a constant). To use error codes, update to the [latest version of the SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview#latest-versions). See [Handle errors](https://platform.claude.com/docs/en/api/handle-errors).
91 
8892### November 3, 2026
8993 
9094* Text generated by Claude Mythos 5, Claude Opus 4.7, and Claude Sonnet 4.6 carries Anthropic’s text watermark on the platforms listed in [How Claude marks AI-generated content](https://support.claude.com/en/articles/16266773-how-claude-marks-ai-generated-content). On Claude Sonnet 4.6, text generated for a request that sets `temperature`, `top_p`, or `top_k` to a non-default value might not carry it. See [Text watermark](https://platform.claude.com/docs/en/build-with-claude/text-watermark).
Feedback