From e04c8fce2425fc31ea38104037117f088247aebf Mon Sep 17 00:00:00 2001 From: Varshith Puli Date: Thu, 23 Jul 2026 22:40:46 +0530 Subject: [PATCH] fix: coerce APIStatusError.code to str to match Optional[str] annotation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 #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 #3531 --- src/openai/_exceptions.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 86f44b0e15..70eb3569a5 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations @@ -71,7 +71,8 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) self.body = body if is_dict(body): - self.code = cast(Any, construct_type(type_=Optional[str], value=body.get("code"))) + code_val = body.get("code") + self.code = str(code_val) if code_val is not None else None self.param = cast(Any, construct_type(type_=Optional[str], value=body.get("param"))) self.type = cast(Any, construct_type(type_=str, value=body.get("type"))) else: