C.W.K.
Stream
Lesson 04 of 06 · published

Typed 에러와 retry 자세

~12 min · errors, retries, discriminated

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

Typed 에러 클래스

SDK가 Python을 mirror한 구체적 에러 클래스 export — BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, RateLimitError, InternalServerError, APIConnectionError. instanceof 분기로 status 코드 parse 없이 retry 자세 작성.

생성자의 maxRetries

클라이언트 생성 시 maxRetries 전달해서 non-streaming 호출의 429/5xx 자동 retry 행동 통제. 디폴트 2. Fast-feedback CLI엔 더 빡빡; long-running batch-style 스크립트엔 더 느슨.

TypeScript의 idempotency

Idempotency key는 per-call options의 headers: { 'Idempotency-Key': key }로 전달. 네트워크 깜빡거림 후 더블 청구 없이 안전하게 retry하고 싶은 비싼 Opus-class 생성에 사용.

원칙: Discriminated 에러 클래스가 HTTP status 코드 분기를 컴파일러 체크 분기로 바꿔. 써.

Code

Retry 자세 위한 instanceof 분기·typescript
import Anthropic, {
  BadRequestError,
  AuthenticationError,
  RateLimitError,
  InternalServerError,
  APIConnectionError,
} from '@anthropic-ai/sdk';

const client = new Anthropic({ maxRetries: 2 });

async function callOnce() {
  try {
    return await client.messages.create({
      model: 'claude-sonnet-4-6',
      max_tokens: 256,
      messages: [{ role: 'user', content: 'hi' }],
    });
  } catch (e) {
    if (e instanceof BadRequestError) throw e;             // 너 버그
    if (e instanceof AuthenticationError) throw e;          // ops 알림
    if (e instanceof RateLimitError) {
      const after = e.headers?.get('retry-after') ?? '2';
      await new Promise(r => setTimeout(r, Number(after) * 1000));
      return callOnce();
    }
    if (e instanceof InternalServerError || e instanceof APIConnectionError) {
      await new Promise(r => setTimeout(r, 2000));
      return callOnce();
    }
    throw e;
  }
}
비싼 호출에 idempotency key·typescript
const idempotencyKey = `claim-${claimId}-summary`;

const resp = await client.messages.create(
  {
    model: 'claude-opus-4-7',
    max_tokens: 4096,
    messages: [{ role: 'user', content: claimText }],
  },
  { headers: { 'Idempotency-Key': idempotencyKey } },
);

External links

Exercise

기존 TypeScript 프로젝트에서 status-code 기반 에러 분기를 SDK export 클래스 대비 instanceof 체크로 교체. 각 에러 클래스 mock하고 올바른 retry 자세 assert하는 unit test 추가.
Hint
BadRequestError가 이제 bubble up해서 테스트 fail하면 그게 옳은 행동 — swallow 대신 요청 모양 고쳐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.