Skip to main content

Error Codes

Complete reference for API error codes with handling examples and troubleshooting tips.

Overview

The Trix API uses conventional HTTP response codes and returns detailed error information to help you diagnose and fix issues quickly.

2xx Success

Request succeeded. Response contains the requested data.

4xx Client Error

Request failed due to client-side issue. Check your request.

5xx Server Error

Request failed due to server issue. Safe to retry.

Error Response Format

All API errors follow a consistent JSON format:

Error Response
{
  "error": {
    "code": "error_code",
    "message": "Human-readable description of what went wrong",
    "details": {
      // Optional additional context
    },
    "request_id": "req_abc123xyz"
  }
}
FieldTypeDescription
error.codestringMachine-readable error code for programmatic handling
error.messagestringHuman-readable description suitable for logging
error.detailsobjectAdditional context (validation errors, limits, etc.)
error.request_idstringUnique ID for this request (include in support tickets)

Always include the request_id when contacting support. It helps us quickly locate your request in our logs.

HTTP Status Codes

StatusMeaningWhen It Happens
200OKRequest succeeded
201CreatedResource created successfully
204No ContentRequest succeeded, no response body (e.g., DELETE)
400Bad RequestInvalid request body or parameters
401UnauthorizedMissing or invalid API key
403ForbiddenValid key but insufficient permissions
404Not FoundResource doesn't exist
409ConflictResource already exists or conflict with current state
422Unprocessable EntityValidation failed
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer error (safe to retry)
502Bad GatewayUpstream service unavailable
503Service UnavailableTemporary maintenance or overload

Error Codes Reference

Authentication Errors

CodeHTTPDescriptionSolution
missing_api_key401No API key providedAdd Authorization: Bearer YOUR_KEY header
invalid_api_key401API key is malformedCheck key format starts with gdb_
expired_api_key401API key has expiredGenerate a new key with trix keys create
revoked_api_key401API key was revokedGenerate a new key
insufficient_permissions403Key lacks required permissionsUse a key with appropriate scopes

Validation Errors

CodeHTTPDescriptionSolution
validation_error422One or more fields failed validationCheck details.fields for specifics
invalid_json400Request body is not valid JSONValidate JSON syntax
missing_required_field422Required field not providedAdd the missing field
invalid_field_type422Field has wrong typeUse correct type (string, number, etc.)
field_too_long422Field exceeds maximum lengthReduce content size
invalid_enum_value422Value not in allowed optionsUse one of the allowed values

Resource Errors

CodeHTTPDescriptionSolution
memory_not_found404Memory with given ID doesn't existVerify the memory ID
space_not_found404Space with given ID doesn't existVerify the space ID
cluster_not_found404Cluster with given ID doesn't existVerify the cluster ID
relationship_not_found404Relationship doesn't existVerify the relationship ID
duplicate_memory409Memory with same content hash existsUpdate existing or use different content
space_already_exists409Space with same name existsUse a different name

Rate Limit Errors

CodeHTTPDescriptionSolution
rate_limit_exceeded429Too many requests per minuteWait for retry_after seconds
daily_limit_exceeded429Daily memory creation limit reachedWait until midnight UTC or upgrade
quota_exceeded403Monthly quota exhaustedUpgrade plan or wait for next cycle
concurrent_limit_exceeded429Too many concurrent requestsReduce parallelism

Server Errors

CodeHTTPDescriptionSolution
internal_error500Unexpected server errorRetry with backoff, contact support if persists
embedding_failed500Failed to generate embeddingsRetry, check content isn't too large
storage_error500Storage operation failedRetry with backoff
service_unavailable503Temporary maintenanceCheck trixdb.com/status

Error Handling Examples

Here's how to handle errors properly in different languages:

import { Trix, TrixError, RateLimitError, ValidationError } from '@trixdb/client';

const trix = new Trix({ apiKey: process.env.TRIX_API_KEY });

async function createMemory(content: string) {
  try {
    const memory = await trix.memories.create({ content });
    return memory;
  } catch (error) {
    if (error instanceof RateLimitError) {
      // Rate limited - wait and retry
      console.log(`Rate limited. Retry after ${error.retryAfter}s`);
      await sleep(error.retryAfter * 1000);
      return createMemory(content); // Retry
    }

    if (error instanceof ValidationError) {
      // Validation failed - log field errors
      console.error('Validation failed:', error.fields);
      throw error; // Don't retry
    }

    if (error instanceof TrixError) {
      // Other API error
      console.error(`API Error [${error.code}]: ${error.message}`);
      console.error(`Request ID: ${error.requestId}`);

      if (error.statusCode >= 500) {
        // Server error - safe to retry
        await sleep(1000);
        return createMemory(content);
      }

      throw error;
    }

    throw error;
  }
}

function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Validation Error Details

Validation errors (HTTP 422) include detailed information about which fields failed and why:

422 Validation Error
{
  "error": {
    "code": "validation_error",
    "message": "Request validation failed",
    "details": {
      "fields": {
        "content": {
          "code": "required",
          "message": "Content is required"
        },
        "priority": {
          "code": "invalid_range",
          "message": "Priority must be between 0 and 10",
          "received": 15,
          "min": 0,
          "max": 10
        },
        "tags": {
          "code": "invalid_type",
          "message": "Tags must be an array of strings",
          "received": "string"
        }
      }
    },
    "request_id": "req_validation_abc123"
  }
}

Handle validation errors by checking each field:

handling-validation.ts
if (error instanceof ValidationError) {
  for (const [field, details] of Object.entries(error.fields)) {
    switch (details.code) {
      case 'required':
        console.log(`Missing required field: ${field}`);
        break;
      case 'invalid_range':
        console.log(`${field} must be between ${details.min} and ${details.max}`);
        break;
      case 'invalid_type':
        console.log(`${field} has wrong type, got ${details.received}`);
        break;
      default:
        console.log(`${field}: ${details.message}`);
    }
  }
}

Rate Limit Errors

Rate limit errors include headers and body data to help you implement proper retry logic:

429 Rate Limit Response
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705312800
Retry-After: 30

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 30 seconds.",
    "details": {
      "limit": 300,
      "remaining": 0,
      "reset": 1705312800,
      "retry_after": 30,
      "window": 60
    },
    "request_id": "req_rate_xyz789"
  }
}

Always respect the Retry-After header. Making requests before this time may result in longer rate limit windows.

See our Rate Limits guide for best practices on handling and avoiding rate limits.

Retry Strategy

Use exponential backoff with jitter for retrying failed requests:

interface RetryConfig {
  maxRetries: number;
  baseDelay: number;
  maxDelay: number;
  retryableErrors: string[];
}

const defaultConfig: RetryConfig = {
  maxRetries: 3,
  baseDelay: 1000,
  maxDelay: 30000,
  retryableErrors: [
    'rate_limit_exceeded',
    'internal_error',
    'storage_error',
    'service_unavailable'
  ]
};

async function withRetry<T>(
  fn: () => Promise<T>,
  config = defaultConfig
): Promise<T> {
  let lastError: Error;

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

      if (error instanceof TrixError) {
        if (!config.retryableErrors.includes(error.code)) {
          throw error;
        }

        const retryAfter = error.details?.retry_after;
        if (retryAfter) {
          await sleep(retryAfter * 1000);
          continue;
        }
      }

      const delay = Math.min(
        config.baseDelay * Math.pow(2, attempt) + Math.random() * 1000,
        config.maxDelay
      );

      console.log(`Retry attempt ${attempt + 1} in ${delay}ms`);
      await sleep(delay);
    }
  }

  throw lastError!;
}

SDK Built-in Retry: The official SDKs include automatic retry logic. Enable it with { retry: { enabled: true } } in your client configuration.

Debugging Tips

Log Request IDs

Always log request_id from errors. Include it when contacting support.

Enable Debug Mode

Set TRIX_DEBUG=true to see full request/response details.

Use trix doctor

Run trix doctor to diagnose connection and auth issues.

Check Status Page

Visit trixdb.com/status for service health.

Terminal
# Run diagnostics
trix doctor

# Enable verbose logging
TRIX_DEBUG=true trix recall "test query"

# Check a specific request
curl -v -H "Authorization: Bearer $TRIX_API_KEY" \
  https://api.trixdb.com/v1/memories/mem_abc123

Getting Help

If you're encountering persistent errors:

  1. Check the Support page for troubleshooting guides
  2. Search the community forum for similar issues
  3. Include the request_id and full error response when asking for help
  4. For urgent issues, email [email protected]

Enterprise plans include priority support with faster response times. Learn more about Enterprise support.