Skip to content

fix(openai): handle non-string error code in classifyOpenAIError#2850

Open
chaodu-agent wants to merge 1 commit into
strands-agents:mainfrom
chaodu-agent:fix/openai-error-code-type-safety
Open

fix(openai): handle non-string error code in classifyOpenAIError#2850
chaodu-agent wants to merge 1 commit into
strands-agents:mainfrom
chaodu-agent:fix/openai-error-code-type-safety

Conversation

@chaodu-agent

Copy link
Copy Markdown

Summary

classifyOpenAIError crashes with TypeError: err.code?.toLowerCase is not a function when used with OpenAI-compatible APIs (e.g., OpenRouter) that return a numeric code in error responses.

Root Cause

The OpenAI SDK's APIError class declares code: string | null | undefined but assigns it directly from the response body without type coercion (this.code = data?.['code']). When an OpenAI-compatible provider like OpenRouter returns { "error": { "code": 400, ... } }, err.code is a number at runtime.

classifyOpenAIError then calls err.code?.toLowerCase() which throws because Number.prototype has no toLowerCase method.

Fix

Use a typeof guard before calling .toLowerCase():

const code = typeof err.code === 'string' ? err.code.toLowerCase() : ''

Also widened the type signature to code?: string | number to reflect runtime reality.

Testing

  • Added test cases for numeric and null error codes
  • All existing tests in errors.test.ts continue to pass

Reproduction

Use the OpenAI model provider with OpenRouter's endpoint (https://openrouter.ai/api/v1) and trigger any error — the agent crashes instead of classifying the error properly.

The OpenAI SDK's APIError.code field is typed as string but can be a
number at runtime when the upstream API (e.g., OpenRouter) returns a
numeric error code in the response body. This causes a TypeError when
calling .toLowerCase() on the value.

Use typeof guard to safely handle non-string code values.
@github-actions github-actions Bot added size/xs typescript Pull requests that update typescript code area-model Related to models or model providers area-devx Developer experience improvements bug Something isn't working labels Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-devx Developer experience improvements area-model Related to models or model providers bug Something isn't working size/xs typescript Pull requests that update typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant