본문 바로가기
C.W.K.
Stream
Lesson 06 of 07 · published

Error Handling — retry 룰

~22 min · errors, retries, exceptions

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

다시 시도할 오류는 시간이 지나면 나아질 수 있는 것뿐이야. RateLimitError(429), APIConnectionError, 5xx server 오류는 일시적일 수 있어. 400, 401, 404, 422 는 요청이나 인증을 고쳐야 하므로 그대로 다시 보내도 해결되지 않아.

tenacity 로 조건과 한도를 함께 적어

@retry(retry=retry_if_exception_type((openai.RateLimitError, openai.APIConnectionError)), wait=wait_exponential_jitter(initial=1, max=20), stop=stop_after_attempt(5)) 는 출발점으로 쓸 만한 설정이야. 어떤 exception 을 다시 시도할지, 얼마나 기다릴지, 몇 번 뒤에 멈출지를 한곳에 드러내.

정확한 exception class 를 잡아

SDK 는 APIError 아래에 APIStatusError, RateLimitError, APIConnectionError 등을 둬. 무조건 except Exception 으로 잡으면 개발자가 중단하려는 신호까지 삼켜 디버깅이 어려워져. 처리할 class 를 정확히 골라.

재시도 기록을 남겨

다시 시도할 때마다 횟수와 실제 대기 시간을 기록해. 운영 환경에서 응답이 느려졌을 때 여러 번 재시도 중이었다는 사실을 바로 확인할 수 있어.

Code

APIStatusError vs APIError 잡기·python
import openai
from openai import OpenAI

client = OpenAI()

try:
    response = client.responses.create(
        model="gpt-5.4", input="Hello!",
    )
except openai.AuthenticationError as e:
    print(f"Auth error: {e}")         # 401
except openai.PermissionDeniedError:
    print("Permission denied")        # 403
except openai.NotFoundError:
    print("Model not found")          # 404
except openai.BadRequestError as e:
    print(f"Bad request: {e.message}") # 400
except openai.RateLimitError as e:
    retry = e.response.headers.get("retry-after")
    print(f"Rate limited, retry after: {retry}")  # 429
except openai.InternalServerError:
    print("Server error")             # 500+
except openai.APIConnectionError as e:
    print(f"Connection error: {e.__cause__}")
except openai.APITimeoutError:
    print("Request timed out")
tenacity 로 retry policy·text
openai.APIError
├── openai.APIConnectionError
│   └── openai.APITimeoutError
├── openai.APIStatusError
│   ├── openai.BadRequestError           (400)
│   ├── openai.AuthenticationError       (401)
│   ├── openai.PermissionDeniedError     (403)
│   ├── openai.NotFoundError             (404)
│   ├── openai.RateLimitError            (429)
│   └── openai.InternalServerError       (500+)

External links

Exercise

retry_chat(messages) 를 작성해 RateLimitError, APIConnectionError, 5xx 에만 지수 backoff 와 jitter 를 적용하고 최대 다섯 번 시도해. 429 를 의도적으로 발생시켜 실제로 기다리는지 확인해.

Progress

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

댓글 0

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

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