---
title: Обработка ошибок
url: https://platform.claude.com/docs/ru/api/handle-errors
description: Используйте SDK, чтобы перехватывать ошибки Claude API по коду ошибки, HTTP-статусу или сбою соединения и обрабатывать ошибку, поступившую в потоке.
---

Используйте SDK, чтобы перехватывать ошибки Claude API по коду ошибки, HTTP-статусу или сбою соединения и обрабатывать ошибку, поступившую в потоке. Чтобы узнать, что означает каждая ошибка, или чтобы вызывать API без SDK, см. [Ошибки Claude API](https://platform.claude.com/docs/ru/api/errors).

<Note>
  Для примеров на этой странице требуется [последняя версия SDK](https://platform.claude.com/docs/ru/cli-sdks-libraries/overview#latest-versions).
</Note>

## Перехват ошибок по типу

В этом примере обрабатываются один [код ошибки](https://platform.claude.com/docs/ru/api/errors#error-codes), один HTTP-статус, сбой соединения и все остальные ответы с ошибками:

<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:
      # Один код ошибки: enforced_spend_limit_reached
      print("Monthly spend cap reached:", e.api_message)
  except anthropic.RateLimitError as e:
      # Один HTTP-статус: любой другой 429
      print("Rate limited. Request ID:", e.request_id)
  except anthropic.APIConnectionError:
      # Ошибка без ответа, например сбой сети или тайм-аут
      print("Connection failed")
  except anthropic.APIStatusError as e:
      # Любой другой ответ с ошибкой
      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) {
      // Один код ошибки: enforced_spend_limit_reached
      console.log("Monthly spend cap reached:", err.apiMessage);
    } else if (err instanceof Anthropic.RateLimitError) {
      // Один HTTP-статус: любой другой 429
      console.log("Rate limited. Request ID:", err.requestID);
    } else if (err instanceof Anthropic.APIConnectionError) {
      // Ошибка без ответа, например сбой сети или тайм-аут
      console.log("Connection failed");
    } else if (err instanceof Anthropic.APIError) {
      // Любой другой ответ с ошибкой
      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)
  {
      // Один код ошибки: enforced_spend_limit_reached
      Console.WriteLine($"Monthly spend cap reached: {e.ApiMessage}");
  }
  catch (AnthropicRateLimitException e)
  {
      // Один HTTP-статус: любой другой 429
      Console.WriteLine($"Rate limited. Request ID: {e.RequestID}");
  }
  catch (Exception e) when (e is AnthropicIOException or TaskCanceledException)
  {
      // Ошибка без ответа, например сбой сети или тайм-аут
      Console.WriteLine("Connection failed");
  }
  catch (AnthropicApiException e)
  {
      // Любой другой ответ с ошибкой
      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")),
  	},
  })

  // В Go SDK есть один тип ошибки. Выполняйте ветвление по коду и статусу ошибки.
  var apierr *anthropic.Error
  if errors.As(err, &apierr) {
  	switch {
  	case apierr.ErrorCode() == anthropic.ErrorCodeEnforcedSpendLimitReached:
  		// Один код ошибки: enforced_spend_limit_reached
  		fmt.Println("Monthly spend cap reached:", apierr.Message)
  	case apierr.StatusCode == http.StatusTooManyRequests:
  		// Один HTTP-статус: любой другой 429
  		fmt.Println("Rate limited. Request ID:", apierr.RequestID)
  	default:
  		// Любой другой ответ с ошибкой
  		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 {
  	// Любая другая ошибка, например сбой сети или тайм-аут
  	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) {
          // Один код ошибки: enforced_spend_limit_reached
          IO.println("Monthly spend cap reached: " + e.apiMessage().orElse(""));
      } catch (RateLimitException e) {
          // Один HTTP-статус: любой другой 429
          IO.println("Rate limited. Request ID: " + e.requestId().orElse(""));
      } catch (AnthropicIoException e) {
          // Ошибка без ответа, например сбой сети или тайм-аут
          IO.println("Connection failed");
      } catch (AnthropicServiceException e) {
          // Любой другой ответ с ошибкой
          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) {
      // Один код ошибки: enforced_spend_limit_reached
      echo 'Monthly spend cap reached: ', $e->getAPIMessage(), PHP_EOL;
  } catch (RateLimitException $e) {
      // Один HTTP-статус: любой другой 429
      echo 'Rate limited. Request ID: ', $e->getRequestID(), PHP_EOL;
  } catch (APIConnectionException) {
      // Ошибка без ответа, например сбой сети или тайм-аут
      echo 'Connection failed', PHP_EOL;
  } catch (APIStatusException $e) {
      // Любой другой ответ с ошибкой
      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
    # Один код ошибки: enforced_spend_limit_reached
    puts "Monthly spend cap reached: #{e.api_message}"
  rescue Anthropic::Errors::RateLimitError => e
    # Один HTTP-статус: любой другой 429
    puts "Rate limited. Request ID: #{e.request_id}"
  rescue Anthropic::Errors::APIConnectionError
    # Ошибка без ответа, например сбой сети или тайм-аут
    puts "Connection failed"
  rescue Anthropic::Errors::APIStatusError => e
    # Любой другой ответ с ошибкой
    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>

Ошибка доходит до вашего кода после того, как собственные повторные попытки SDK, если они были, завершились неудачей (см. [Повторные попытки](https://platform.claude.com/docs/ru/api/errors#retries)). Чтобы узнать, что означает каждый статус, см. [Ошибки HTTP](https://platform.claude.com/docs/ru/api/errors#http-errors).

Располагайте узкий случай перед широким. Messages API возвращает `enforced_spend_limit_reached` — код для [месячного предела расходов](https://platform.claude.com/docs/ru/api/rate-limits#reaching-your-spend-cap) — со статусом 429. Если бы ветка для 429 шла первой, она перехватывала бы и этот код.

Чтобы обработать другой случай, например 404, см. [Типы ошибок SDK](https://platform.claude.com/docs/ru/api/errors#sdk-error-types).

## Обработка конкретного кода ошибки

Чтобы обработать другой код ошибки, добавьте его ветку в раздел [Перехват ошибок по типу](https://platform.claude.com/docs/ru/api/handle-errors#catch-errors-by-kind) перед любой более широкой веткой.

У каждого кода есть собственный класс или константа, названные по этому коду, например `anthropic.EnforcedSpendLimitReachedError` (typescript: `Anthropic.EnforcedSpendLimitReachedError`; ruby: `Anthropic::EnforcedSpendLimitReachedError`; java: `com.anthropic.models.EnforcedSpendLimitReachedException`; php: `Anthropic\EnforcedSpendLimitReachedException`; csharp: `Anthropic.Models.AnthropicEnforcedSpendLimitReachedException`; go: `anthropic.ErrorCodeEnforcedSpendLimitReached`). Классы для других кодов могут находиться в других пространствах имён. Чтобы найти нужный, выполните поиск имени класса в исходном коде SDK. В документирующем комментарии метода перечислены класс или константа для каждого кода, который может вернуть метод.

Полный список кодов см. в [`ErrorDetails`](https://platform.claude.com/docs/ru/api/$shared#error_details) в справочнике API.

## Обработка ошибки в потоке

После начала потока API уже вернул статус 200, поэтому ошибку он отправляет как [событие ошибки](https://platform.claude.com/docs/ru/build-with-claude/streaming#error-events). SDK не выполняет повторных попыток запроса.

Каждое событие ошибки поступает к вам как `APIStatusError` (typescript: `APIError`; csharp: `AnthropicSseException`; java: `SseException`; php: `APIStatusException`; go: `*anthropic.Error`). Его HTTP-статус — это статус потока 200, либо он отсутствует. Поэтому ветка для одного статуса или для класса одного кода его не перехватит. Вместо этого проверяйте, соответствует ли его `error.type` одному из типов, описанных в разделе [Ошибки HTTP](https://platform.claude.com/docs/ru/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":
          # Один error.type: overloaded_error
          print("\nOverloaded:", e.api_message)
      else:
          raise
  ```

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

  try {
    await client.messages
      .stream({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages: [{ role: "user", content: "Hello, Claude" }]
      })
      .on("text", (text) => {
        process.stdout.write(text);
      })
      .finalMessage();
  } catch (err) {
    if (err instanceof Anthropic.APIError && err.type === "overloaded_error") {
      // Один error.type: overloaded_error
      console.log("\nOverloaded:", err.apiMessage);
    } else {
      throw err;
    }
  }
  ```

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

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new UserMessageParam { Content = "Hello, Claude" }]
  };

  try
  {
      await foreach (var streamEvent in client.Messages.CreateStreaming(parameters))
      {
          if (
              streamEvent.TryPickContentBlockDelta(out var deltaEvent)
              && deltaEvent.Delta.TryPickText(out var textDelta)
          )
          {
              Console.Write(textDelta.Text);
          }
      }
  }
  // Базовый класс для AnthropicSseException (события ошибок)
  // и AnthropicApiException (ответы с ошибками)
  catch (AnthropicServiceException e) when (e.Type?.Raw() == "overloaded_error")
  {
      // Один error.type: overloaded_error
      Console.WriteLine($"\nOverloaded: {e.ApiMessage}");
  }
  ```

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

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

  for stream.Next() {
  	event := stream.Current()
  	switch eventVariant := event.AsAny().(type) {
  	case anthropic.ContentBlockDeltaEvent:
  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {
  		case anthropic.TextDelta:
  			fmt.Print(deltaVariant.Text)
  		}
  	}
  }

  err := stream.Err()
  var apierr *anthropic.Error
  if errors.As(err, &apierr) && apierr.Type() == anthropic.ErrorTypeOverloadedError {
  	// Один error.type: overloaded_error
  	fmt.Println("\nOverloaded:", apierr.Message)
  } else if err != nil {
  	log.Fatal(err)
  }
  ```

  ```java Java
  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.errors.AnthropicServiceException;
  import com.anthropic.models.ErrorType;
  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 (var streamResponse = client.messages().createStreaming(params)) {
          streamResponse.stream().forEach(event -> {
              event.contentBlockDelta().ifPresent(deltaEvent ->
                  deltaEvent.delta().text().ifPresent(textDelta ->
                      IO.print(textDelta.text())
                  )
              );
          });
      } catch (AnthropicServiceException e) {
          // Перехватывает события ошибок (SseException) и ответы с ошибками
          if (ErrorType.OVERLOADED_ERROR.equals(e.type().orElse(null))) {
              // Один error.type: overloaded_error
              IO.println("\nOverloaded: " + e.apiMessage().orElse(""));
          } else {
              throw e;
          }
      }
  }
  ```

  ```php PHP
  use Anthropic\Core\Exceptions\APIStatusException;
  use Anthropic\Messages\Model;
  use Anthropic\Messages\RawContentBlockDeltaEvent;
  use Anthropic\Messages\TextDelta;

  $client = new Client();

  try {
      $stream = $client->messages->createStream(
          model: Model::CLAUDE_OPUS_5_5,
          maxTokens: 1024,
          messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      );

      foreach ($stream as $event) {
          if (
              $event instanceof RawContentBlockDeltaEvent
              && $event->delta instanceof TextDelta
          ) {
              echo $event->delta->text;
          }
      }
  } catch (APIStatusException $e) {
      if ($e->getType() === 'overloaded_error') {
          // Один error.type: overloaded_error
          echo PHP_EOL, 'Overloaded: ', $e->getAPIMessage(), PHP_EOL;
      } else {
          throw $e;
      }
  }
  ```

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

  begin
    stream = client.messages.stream(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello, Claude" }]
    )

    stream.text.each { |text| print(text) }
  rescue Anthropic::Errors::APIStatusError => e
    if e.type == :overloaded_error
      # Один error.type: overloaded_error
      puts "\nOverloaded: #{e.api_message}"
    else
      raise
    end
  end
  ```
</CodeGroup>

У события ошибки также может быть [код ошибки](https://platform.claude.com/docs/ru/api/errors#error-codes). Прочитайте его из `error_code` (typescript: `errorCode`; csharp: `ErrorCode`; java: `errorCode().orElse(null)`; php: `getErrorCode()`; go: `ErrorCode()`) и сравните с кодом, который вы хотите обработать, например `"enforced_spend_limit_reached"` (ruby: `:enforced_spend_limit_reached`; go: `anthropic.ErrorCodeEnforcedSpendLimitReached`).

Поток может завершиться сбоем ещё двумя способами:

* **Запрос завершается ошибкой до начала потока:** вы получаете ошибки, описанные в разделе [Перехват ошибок по типу](https://platform.claude.com/docs/ru/api/handle-errors#catch-errors-by-kind).
* **Соединение обрывается посреди потока:** событие ошибки не поступает, и ветка для соединения в разделе [Перехват ошибок по типу](https://platform.claude.com/docs/ru/api/handle-errors#catch-errors-by-kind) может не перехватить ошибку. Чтобы узнать, что её перехватывает, см. [Типы ошибок SDK](https://platform.claude.com/docs/ru/api/errors#sdk-error-types).

Чтобы продолжить ответ после сбоя потока, см. [Восстановление после ошибок](https://platform.claude.com/docs/ru/build-with-claude/streaming#error-recovery).
