Skip to content

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

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

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
@amirhosseinghanipour

Copy link
Copy Markdown

Same fix as the one in #3532. Two notes:

  1. Line 1 has an unintended change. Worth reverting that. It's noise unrelated to the fix and will likely trip up diffing/linting.
  2. No test was added for this. fix: normalize API error codes to strings #3532 includes one. Consider deferring to that PR since it covers the same fix with a regression test.

@Varshith-Kali

Copy link
Copy Markdown
Author

Thanks @amirhosseinghanipour for the review. You're right — #3532 already covers this with a proper regression test, and this PR has an unintended line-1 diff. Closing in favor of #3532.

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

2 participants