Implementation:Openai Openai node Error Classes
| Knowledge Sources | |
|---|---|
| Domains | SDK, Error_Handling |
| Last Updated | 2026-02-15 12:00 GMT |
Overview
The error module defines the complete error class hierarchy used by the openai-node SDK to represent API failures, connection issues, and content filtering events.
Description
At the root of the hierarchy is OpenAIError, a simple Error subclass serving as the base for all SDK-specific errors. The primary workhorse is APIError, a generic class parameterized by HTTP status code, headers, and error body types. It captures the HTTP status, response headers, the parsed JSON error body, and extracts code, param, type, and requestID (from the x-request-id header) fields for structured error inspection.
APIError provides a static generate() factory method that maps HTTP status codes to the appropriate specialized subclass: BadRequestError (400), AuthenticationError (401), PermissionDeniedError (403), NotFoundError (404), ConflictError (409), UnprocessableEntityError (422), RateLimitError (429), and InternalServerError (500+). When no status or headers are available, it produces an APIConnectionError.
Additional error classes handle specific scenarios: APIUserAbortError for user-cancelled requests, APIConnectionError and APIConnectionTimeoutError for network-level failures, LengthFinishReasonError and ContentFilterFinishReasonError for response parsing failures due to length limits or content policy rejections, and InvalidWebhookSignatureError for webhook verification failures.
Usage
These error classes are thrown automatically by the SDK when API requests fail. Developers can catch specific subclasses for targeted error handling (e.g., retrying on RateLimitError, re-authenticating on AuthenticationError). The requestID property is particularly useful for support escalations.
Code Reference
Source Location
- Repository: openai-node
- File: src/core/error.ts
Signature
export class OpenAIError extends Error {}
export class APIError<
TStatus extends number | undefined = number | undefined,
THeaders extends Headers | undefined = Headers | undefined,
TError extends Object | undefined = Object | undefined,
> extends OpenAIError {
readonly status: TStatus;
readonly headers: THeaders;
readonly error: TError;
readonly code: string | null | undefined;
readonly param: string | null | undefined;
readonly type: string | undefined;
readonly requestID: string | null | undefined;
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders);
static generate(
status: number | undefined,
errorResponse: Object | undefined,
message: string | undefined,
headers: Headers | undefined,
): APIError;
}
export class APIUserAbortError extends APIError<undefined, undefined, undefined> {}
export class APIConnectionError extends APIError<undefined, undefined, undefined> {}
export class APIConnectionTimeoutError extends APIConnectionError {}
export class BadRequestError extends APIError<400, Headers> {}
export class AuthenticationError extends APIError<401, Headers> {}
export class PermissionDeniedError extends APIError<403, Headers> {}
export class NotFoundError extends APIError<404, Headers> {}
export class ConflictError extends APIError<409, Headers> {}
export class UnprocessableEntityError extends APIError<422, Headers> {}
export class RateLimitError extends APIError<429, Headers> {}
export class InternalServerError extends APIError<number, Headers> {}
export class LengthFinishReasonError extends OpenAIError {}
export class ContentFilterFinishReasonError extends OpenAIError {}
export class InvalidWebhookSignatureError extends Error {}
Import
import OpenAI from 'openai';
// All error classes are available on the OpenAI namespace
OpenAI.APIError;
OpenAI.AuthenticationError;
OpenAI.RateLimitError;
// etc.
// Or import directly
import {
APIError,
AuthenticationError,
RateLimitError,
BadRequestError,
} from 'openai';
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| status | undefined | Yes | The HTTP status code from the response. undefined for connection-level errors.
|
| error | undefined | Yes | The parsed JSON error body from the API response. |
| message | undefined | No | A fallback error message when the error body does not contain one. |
| headers | undefined | Yes | The HTTP response headers. undefined for connection-level errors.
|
Outputs
| Name | Type | Description |
|---|---|---|
| status | undefined | The HTTP status code. |
| headers | undefined | The HTTP response headers. |
| error | undefined | The parsed error body from the API. |
| code | null | undefined | The error code from the API error body. |
| param | null | undefined | The parameter that caused the error, if applicable. |
| type | undefined | The error type from the API error body. |
| requestID | null | undefined | The request ID from the x-request-id response header.
|
| message | string |
A human-readable error message combining status and error details. |
Usage Examples
import OpenAI from 'openai';
const client = new OpenAI();
try {
await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }],
});
} catch (err) {
if (err instanceof OpenAI.RateLimitError) {
console.log('Rate limited, retrying after delay...');
console.log('Request ID:', err.requestID);
} else if (err instanceof OpenAI.AuthenticationError) {
console.error('Invalid API key:', err.message);
} else if (err instanceof OpenAI.APIConnectionError) {
console.error('Network issue:', err.message);
} else if (err instanceof OpenAI.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
console.error('Error code:', err.code);
console.error('Error type:', err.type);
}
}