Pinecone TypeScript SDK - v9.0.0
    Preparing search index...

    Error Handling

    The Pinecone TypeScript SDK provides a hierarchy of error classes to help you handle different failure scenarios appropriately. All custom errors extend Errors.BasePineconeError.

    For more information on error handling in production, see Error handling.

    The error classes are not top-level exports. They are grouped under a single Errors namespace, which is a top-level export of the package:

    import { Errors } from '@pinecone-database/pinecone';

    function isNotFound(error: unknown): boolean {
    return error instanceof Errors.PineconeNotFoundError;
    }

    Every class listed below is reached through that namespace, for example Errors.PineconeNotFoundError. The examples in this guide follow that convention.

    Note also that under TypeScript's strict mode a catch (error) binding has type unknown, so you cannot read error.message or error.name until you have narrowed the type. An instanceof check against one of these classes performs that narrowing, which is why every example below reads error properties only inside an instanceof branch.

    The SDK includes the following error classes, all reachable as Errors.<ClassName>:

    • PineconeBadRequestError (400, 403) - Invalid request parameters or insufficient quota
    • PineconeAuthorizationError (401) - Invalid or missing API key
    • PineconePaymentRequiredError (402) - Billing problem, such as quota exhaustion or a declined card
    • PineconeNotFoundError (404) - Resource not found
    • PineconeMethodNotAllowedError (405) - HTTP method not supported for this endpoint
    • PineconeConflictError (409) - Resource already exists
    • PineconeFailedPreconditionError (412) - A precondition the request depended on no longer holds
    • PineconeUnprocessableEntityError (422) - Request was well-formed but semantically invalid
    • PineconeInternalServerError (500) - Pinecone server error
    • PineconeNotImplementedError (501) - Feature not available on your plan
    • PineconeUnavailableError (503) - Service temporarily unavailable
    • PineconeUnmappedHttpError - Unexpected HTTP error
    • PineconeConfigurationError - Invalid client configuration
    • PineconeEnvironmentVarsNotSupportedError - Environment variable issue
    • PineconeUnableToResolveHostError - Cannot resolve index host
    • PineconeConnectionError - Network connection failure
    • PineconeRequestError - General request failure
    • PineconeMaxRetriesExceededError - Exceeded maximum retry attempts
    • PineconeArgumentError - Invalid function arguments

    Catch and handle specific errors to implement appropriate recovery strategies:

    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function handleSpecificErrors() {
    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });

    try {
    const indexModel = await pc.indexes.describe('my-index');
    const index = pc.index({ host: indexModel.host });
    const results = await index.query({
    vector: [0.1, 0.2, 0.3],
    topK: 10,
    });
    console.log(results);
    } catch (error) {
    if (error instanceof Errors.PineconeAuthorizationError) {
    console.error('Invalid API key. Please check your credentials.');
    // Prompt user to update API key
    } else if (error instanceof Errors.PineconeNotFoundError) {
    console.error('Index not found. Please create the index first.');
    // Create the index or use different index name
    } else if (error instanceof Errors.PineconeConnectionError) {
    console.error('Connection failed. Retrying...');
    // Implement retry logic
    } else if (error instanceof Errors.PineconeBadRequestError) {
    console.error('Invalid request parameters:', error.message);
    // Fix request parameters
    } else {
    console.error('Unexpected error:', error);
    throw error; // Re-throw if unhandled
    }
    }
    }

    handleSpecificErrors();

    All Pinecone errors include helpful properties:

    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function examineErrorProperties() {
    const pc = new Pinecone({ apiKey: 'INVALID_KEY' });

    try {
    await pc.indexes.list();
    } catch (error) {
    if (error instanceof Errors.BasePineconeError) {
    console.error('Error name:', error.name);
    console.error('Error message:', error.message);
    console.error('Error stack:', error.stack);

    // Access the cause if the error was wrapped
    if (error.cause) {
    console.error('Underlying cause:', error.cause);
    }
    }
    }
    }

    examineErrorProperties();

    Implement retry logic for transient failures:

    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function retryableOperation<T>(
    operation: () => Promise<T>,
    maxRetries: number = 3,
    ): Promise<T> {
    let lastError: Error;

    for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
    return await operation();
    } catch (error) {
    lastError = error as Error;

    // Only retry on transient errors
    const isRetryable =
    error instanceof Errors.PineconeConnectionError ||
    error instanceof Errors.PineconeInternalServerError ||
    error instanceof Errors.PineconeUnavailableError;

    if (isRetryable && attempt < maxRetries - 1) {
    const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
    console.log(`Attempt ${attempt + 1} failed. Retrying in ${delay}ms...`);
    await new Promise((resolve) => setTimeout(resolve, delay));
    } else {
    throw error;
    }
    }
    }

    throw lastError!;
    }

    // Usage
    async function queryWithRetry() {
    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });
    const indexModel = await pc.indexes.describe('my-index');
    const index = pc.index({ host: indexModel.host });

    const results = await retryableOperation(() =>
    index.query({
    vector: [0.1, 0.2, 0.3],
    topK: 10,
    }),
    );

    return results;
    }

    queryWithRetry();

    The Pinecone client supports automatic retries for certain operations. Configure this when creating the client:

    import { Pinecone } from '@pinecone-database/pinecone';

    const pc = new Pinecone({
    apiKey: 'YOUR_API_KEY',
    maxRetries: 5, // Retry up to 5 times (default is 3)
    });

    // Operations like upsert, update, and configureIndex will automatically retry
    const indexModel = await pc.indexes.describe('my-index');
    const index = pc.index({ host: indexModel.host });
    await index.upsert({
    records: [{ id: '1', values: [0.1, 0.2, 0.3] }],
    });

    Errors.PineconeArgumentError is thrown when arguments fail the client's runtime validation. Many of those same mistakes are also caught by the type system before the code ever runs, so the example below has to defeat the compiler deliberately in order to reach the runtime check. Keep the runtime handler for arguments that TypeScript cannot see, such as records assembled from JSON or from a JavaScript caller.

    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function handleValidationErrors() {
    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });
    const indexModel = await pc.indexes.describe('my-index');
    const index = pc.index({ host: indexModel.host });

    try {
    // Missing required 'id' field
    await index.upsert({
    records: [
    // @ts-expect-error - missing id
    {
    values: [0.1, 0.2, 0.3],
    },
    ],
    });
    } catch (error) {
    if (error instanceof Errors.PineconeArgumentError) {
    console.error('Invalid arguments:', error.message);
    // Fix the arguments and retry
    }
    }
    }

    handleValidationErrors();

    Here's a comprehensive example showing robust error handling:

    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function robustIndexOperation() {
    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY', maxRetries: 3 });

    try {
    // Try to create an index
    await pc.indexes.create({
    name: 'my-index',
    dimension: 1536,
    spec: {
    serverless: {
    cloud: 'aws',
    region: 'us-east-1',
    },
    },
    suppressConflicts: true, // Don't throw if index exists
    });

    const indexModel = await pc.indexes.describe('my-index');
    const index = pc.index({ host: indexModel.host });

    // Perform operations with proper error handling
    const results = await index.query({
    vector: [0.1, 0.2, 0.3],
    topK: 10,
    });

    return results;
    } catch (error) {
    if (error instanceof Errors.PineconeAuthorizationError) {
    console.error('Authentication failed. Check your API key.');
    process.exit(1);
    } else if (error instanceof Errors.PineconeNotFoundError) {
    console.error('Resource not found.');
    // Could create the resource here
    } else if (error instanceof Errors.PineconeConnectionError) {
    console.error('Connection failed. Check your network.');
    // Could retry or use fallback
    } else if (error instanceof Errors.PineconeBadRequestError) {
    console.error('Invalid request:', error.message);
    // Fix request parameters
    } else if (error instanceof Errors.PineconeConflictError) {
    console.log('Resource already exists, continuing...');
    // Not necessarily an error
    } else if (error instanceof Errors.BasePineconeError) {
    console.error('Pinecone error:', error.message);
    throw error;
    } else {
    console.error('Unexpected error:', error);
    throw error;
    }
    }
    }

    robustIndexOperation();

    Enable debug logging to troubleshoot issues:

    import { Pinecone } from '@pinecone-database/pinecone';

    // Set environment variable for debug logging
    process.env.PINECONE_DEBUG = 'true';

    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });

    // Operations will now log detailed information
    await pc.indexes.list();

    You can also enable CURL command logging:

    // Log equivalent CURL commands for all requests
    process.env.PINECONE_DEBUG_CURL = 'true';
    1. Catch specific errors: Handle different error types appropriately
    2. Retry transient failures: Implement exponential backoff for connection errors
    3. Use suppressConflicts: For idempotent operations like pc.indexes.create
    4. Log errors: Log errors with context for debugging
    5. Wrap errors: When wrapping errors, preserve the original cause
    6. Check status page: For 500/503 errors, check status.pinecone.io
    7. Validate early: Catch validation errors before making API calls
    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function createOrUseExisting(name: string) {
    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });

    try {
    await pc.indexes.create({
    name,
    dimension: 1536,
    spec: {
    serverless: {
    cloud: 'aws',
    region: 'us-east-1',
    },
    },
    });
    console.log('Index created successfully');
    } catch (error) {
    if (error instanceof Errors.PineconeConflictError) {
    console.log('Index already exists, using existing index');
    } else {
    throw error;
    }
    }

    return pc.index({ name });
    }
    import { Pinecone, Errors } from '@pinecone-database/pinecone';

    async function queryWithFallback() {
    const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });
    const indexModel = await pc.indexes.describe('my-index');
    const index = pc.index({ host: indexModel.host });

    try {
    const results = await index.query({
    vector: [0.1, 0.2, 0.3],
    topK: 10,
    });
    return results;
    } catch (error) {
    if (error instanceof Errors.PineconeConnectionError) {
    console.warn('Pinecone unavailable, using cached results');
    // Return cached results or empty response
    return { matches: [], namespace: '', usage: { readUnits: 0 } };
    }
    throw error;
    }
    }

    For more information on async patterns, see Async Patterns.