Skip to content

fix: coerce APIStatusError.code to str to match Optional[str] annotation#3536

Open
Varshith-Kali wants to merge 1 commit into
openai:mainfrom
Varshith-Kali:fix/api-status-error-code-coerce
Open

fix: coerce APIStatusError.code to str to match Optional[str] annotation#3536
Varshith-Kali wants to merge 1 commit into
openai:mainfrom
Varshith-Kali:fix/api-status-error-code-coerce

Conversation

@Varshith-Kali

Copy link
Copy Markdown

Summary

Fixes #3531APIStatusError.code is annotated Optional[str] but construct_type(type_=Optional[str], value=...) passes through non-str values unchanged (int, bool, etc.), and the cast(Any, ...) silences the type checker. Downstream code that trusts the annotation and calls exc.code.strip() crashes with AttributeError.

Fix

Replace the construct_type + cast pattern with an explicit str() coercion guarded by a None check:

  • Non-None code values (int, bool, float, etc.) → str(value)
  • NoneNone (unchanged)
  • String codes pass through str() as identity (unchanged)

Testing

Verified all six coercion cases pass:

  • {"code": 404}"404"
  • {"code": "rate_limit"}"rate_limit"
  • {"message": "nope"}None
  • {"code": true}"True"
  • {"code": null}None
  • Not a dict body → None

The lenient construct_type(type_=Optional[str], ...) passes through
non-str values (int, bool, etc.) unchanged, while the cast(Any, ...)
silences the type checker. When an API response contains a JSON number
for error.code, exc.code is an int at runtime despite the Optional[str]
annotation — causing downstream AttributeError on .strip() as reported
in openai#3531.

Fix: replace the construct_type+cast pattern with an explicit str()
coercion guarded by a None check. Existing string codes pass through
unchanged; None stays None; everything else becomes its str repr.

Fixes openai#3531
@Varshith-Kali
Varshith-Kali requested a review from a team as a code owner July 23, 2026 17:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

APIStatusError.code is typed Optional[str] but can be an int at runtime

1 participant