/** * General error handler for API provider errors * Transforms technical errors into user-friendly messages while preserving metadata * * This utility ensures consistent error handling across all API providers: * - Preserves HTTP status codes for UI-aware error display * - Maintains error details for retry logic (e.g., RetryInfo for 429 errors) * - Provides consistent error message formatting * - Enables telemetry and debugging with complete error context */ import { APIUserAbortError } from "openai" import i18n from "../../../i18n/setup" import { createAbortError, isTimeoutAbort } from "./abort-signal" import { createTimeoutError } from "./request-timeout" /** * Handles API provider errors and transforms them into user-friendly messages * while preserving important metadata for retry logic and UI display. * * @param error - The error to handle * @param providerName - The name of the provider for context in error messages * @param options - Optional configuration for error handling * @returns A wrapped Error with preserved metadata (status, errorDetails, code) * * @example * // Basic usage * try { * await apiClient.createMessage(...) * } catch (error) { * throw handleProviderError(error, "OpenAI") * } * * @example * // With custom message prefix * catch (error) { * throw handleProviderError(error, "Anthropic", { messagePrefix: "streaming" }) * } */ /** * Whether the error carries a numeric HTTP status (SDK APIs expose it as * `status` or, for the AI SDK, `statusCode`). * * Use before classifying a failure purely by cancellation state: a terminal * API failure (401/429/5xx) can land in the same tick as an abort, and it must * keep its own identity so retry, backoff and the UI still see the provider * error instead of a cancellation. */ export function hasNumericHttpStatus(error: unknown): boolean { if (!error || typeof error !== "object") return false const candidate = error as { status?: unknown; statusCode?: unknown } for (const status of [candidate.status, candidate.statusCode]) { // Number.isFinite does not coerce, so it already rejects every non-number; // a separate typeof check would be dead weight (and an equivalent mutant). if (Number.isFinite(status)) return true } return false } /** * The numeric HTTP status carried by an error, or `undefined` when it carries none. * Same field order as hasNumericHttpStatus — `status` (most SDKs expose it that way) * before `statusCode` (the AI SDK's APICallError shape) — and only finite numbers, * so a null or stringy status never becomes a retry header or a telemetry property. */ export function getNumericHttpStatus(error: unknown): number | undefined { if (!error || typeof error !== "object") return undefined const candidate = error as { status?: unknown; statusCode?: unknown } // Number.isFinite does not coerce, so the value it accepted has to be handed back // with a cast: there is no narrower form for an already-validated unknown number. if (Number.isFinite(candidate.status)) return candidate.status as number return Number.isFinite(candidate.statusCode) ? (candidate.statusCode as number) : undefined } export function handleProviderError( error: unknown, providerName: string, options?: { /** Custom message prefix (default: "completion") */ messagePrefix?: string /** Custom message transformer */ messageTransformer?: (msg: string) => string }, ): Error { const messagePrefix = options?.messagePrefix || "completion" if (error instanceof Error) { const anyErr = error as any const msg = anyErr?.error?.metadata?.raw || error.message || "" // Log the original error details for debugging console.error(`[${providerName}] API error:`, { message: msg, name: error.name, stack: error.stack, status: anyErr.status, statusCode: anyErr.statusCode, }) let wrapped: Error // Special case: Invalid character/ByteString conversion error in API key // This is specific to OpenAI-compatible SDKs if (msg.includes("Cannot convert argument to a ByteString")) { wrapped = new Error(i18n.t("common:errors.api.invalidKeyInvalidChars")) } else { // Apply custom transformer if provided, otherwise use default format const finalMessage = options?.messageTransformer ? options.messageTransformer(msg) : `${providerName} ${messagePrefix} error: ${msg}` wrapped = new Error(finalMessage) } // Preserve HTTP status and structured details for retry/backoff + UI // These fields are used by Task.backoffAndAnnounce() and ChatRow/ErrorRow // to provide status-aware error messages and handling. AI SDK errors (e.g., // APICallError) expose the HTTP status as `statusCode` instead of `status`, // so fall back to it: a real 429 must reach Task.backoffAndAnnounce's .status check. // Only a numeric status can drive backoff: a null or nonnumeric status // would be echoed straight into the retry header, so take a numeric status // first and fall back to a numeric statusCode. const numericStatus = typeof anyErr.status === "number" ? anyErr.status : undefined const numericStatusCode = typeof anyErr.statusCode === "number" ? anyErr.statusCode : undefined const preservedStatus = numericStatus !== undefined ? numericStatus : numericStatusCode if (preservedStatus !== undefined) { ;(wrapped as any).status = preservedStatus } if (anyErr.errorDetails !== undefined) { ;(wrapped as any).errorDetails = anyErr.errorDetails } if (anyErr.code !== undefined) { ;(wrapped as any).code = anyErr.code } // Preserve AWS-specific metadata if present (for Bedrock) if (anyErr.$metadata !== undefined) { ;(wrapped as any).$metadata = anyErr.$metadata } return wrapped } // Non-Error: wrap with provider-specific prefix console.error(`[${providerName}] Non-Error exception:`, error) const wrapped = new Error(`${providerName} ${messagePrefix} error: ${String(error)}`) // Also try to preserve status for non-Error exceptions (e.g., plain objects with // status or statusCode, matching the AI SDK APICallError shape) const anyErr = error as any const plainStatus = typeof anyErr?.status === "number" ? anyErr.status : typeof anyErr?.statusCode === "number" ? anyErr.statusCode : undefined if (plainStatus !== undefined) { ;(wrapped as any).status = plainStatus } return wrapped } /** * Specialized handler for OpenAI-compatible providers * Re-exports with OpenAI-specific defaults for backward compatibility */ export function handleOpenAIError(error: unknown, providerName: string): Error { return handleProviderError(error, providerName, { messagePrefix: "completion" }) } /** * Handles errors from OpenAI Node SDK request sites with abort awareness. * * An abort failure (the external signal already aborted, the SDK's * APIUserAbortError, or a fetch-level AbortError) is normalized to a fresh * Error with name "AbortError" and a message ending in "aborted" (the Task.ts * contract) instead of being wrapped as a regular completion error, which a * plain rethrow of the SDK abort error would produce. * * @internal Exported for the provider request sites that adopt it in the follow-up * #1311 splits; direct contract tests cover it here (docs/development-quality-checks.md * "intentional direct-test seam"). */ export function handleOpenAIRequestError( error: unknown, providerName: string, abortSignal?: AbortSignal, requestSignal?: AbortSignal, ): Error { // A terminal HTTP failure keeps its own identity even when the caller stops in the same tick: // backoff reads the top-level status, so masking a 401/429 as AbortError hides the provider error. if (hasNumericHttpStatus(error)) return handleOpenAIError(error, providerName) // The deadline, not the caller's stop, ended this request. Classified before the abort branch so a // native AbortError raised by the SDK's JSON body read is reported as a timeout as well. if (!abortSignal?.aborted && isTimeoutAbort(requestSignal)) { // The abort came from this merged signal's own deadline, not the caller's stop: a timeout // must stay distinguishable from a user cancellation, so the shared helper's name and // message are used and the SDK abort is attached as the cause. A caller that pressed stop // never reaches here - error-handler.spec.ts:483-492 pins the abort for that interleaving. const timeoutError = createTimeoutError(providerName, "completion request") timeoutError.cause = error return timeoutError } if ( abortSignal?.aborted || (error instanceof Error && (error.name === "AbortError" || error instanceof APIUserAbortError)) ) { return createAbortError(providerName, error) } return handleOpenAIError(error, providerName) }