---
title: 오류 처리
url: https://platform.claude.com/docs/ko/api/handle-errors
description: SDK를 사용하여 오류 코드, HTTP 상태 또는 연결 실패별로 Claude API 오류를 포착하고, 스트림에서 도착하는 오류를 처리합니다.
---

SDK를 사용하여 오류 코드, HTTP 상태 또는 연결 실패별로 Claude API 오류를 포착하고, 스트림에서 도착하는 오류를 처리합니다. 각 오류의 의미를 알아보거나 SDK 없이 API를 호출하려면 [Claude API 오류](https://platform.claude.com/docs/ko/api/errors)를 참조하세요.

<Note>
  이 페이지의 예제에는 [최신 버전의 SDK](https://platform.claude.com/docs/ko/cli-sdks-libraries/overview#latest-versions)가 필요합니다.
</Note>

## 종류별로 오류 포착하기

이 예제는 하나의 [오류 코드](https://platform.claude.com/docs/ko/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/ko/api/errors#retries) 참조). 각 상태의 의미는 [HTTP 오류](https://platform.claude.com/docs/ko/api/errors#http-errors)를 참조하세요.

좁은 범위의 케이스를 넓은 범위의 케이스보다 앞에 두세요. Messages API는 [월간 지출 상한](https://platform.claude.com/docs/ko/api/rate-limits#reaching-your-spend-cap)에 대한 코드인 `enforced_spend_limit_reached`를 429와 함께 반환합니다. 429에 대한 분기가 먼저 오면 해당 코드도 그 분기에서 포착됩니다.

404와 같은 다른 케이스를 처리하려면 [SDK 오류 유형](https://platform.claude.com/docs/ko/api/errors#sdk-error-types)을 참조하세요.

## 특정 오류 코드 처리하기

다른 오류 코드를 처리하려면 [종류별로 오류 포착하기](https://platform.claude.com/docs/ko/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 소스에서 클래스 이름을 검색하세요. 메서드의 문서 주석에는 해당 메서드가 반환할 수 있는 각 코드에 대한 클래스나 상수가 나열되어 있습니다.

전체 코드 목록은 API 레퍼런스의 [`ErrorDetails`](https://platform.claude.com/docs/ko/api/$shared#error_details)를 참조하세요.

## 스트림에서 오류 처리하기

스트림이 시작된 후에는 API가 이미 200을 반환했으므로, 오류를 [오류 이벤트](https://platform.claude.com/docs/ko/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/ko/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/ko/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/ko/api/handle-errors#catch-errors-by-kind)에 있는 오류를 받게 됩니다.
* **스트림 도중에 연결이 끊어지는 경우:** 오류 이벤트가 도착하지 않으며, [종류별로 오류 포착하기](https://platform.claude.com/docs/ko/api/handle-errors#catch-errors-by-kind)의 연결 분기가 오류를 포착하지 못할 수 있습니다. 어떤 분기가 포착하는지 알아보려면 [SDK 오류 유형](https://platform.claude.com/docs/ko/api/errors#sdk-error-types)을 참조하세요.

스트림이 실패한 후 응답을 이어서 받으려면 [오류 복구](https://platform.claude.com/docs/ko/build-with-claude/streaming#error-recovery)를 참조하세요.
