> ## Documentation Index
> Fetch the complete documentation index at: https://docs.prisme.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Errors

> Understanding and handling Prisme.ai API errors

The Prisme.ai API uses conventional HTTP response codes to indicate the success or failure of an API request. This page provides a comprehensive guide to understanding and handling errors from the API.

## Error Response Format

All API errors follow a consistent format:

```json theme={null}
{
  "error": "error_code",
  "message": "A human-readable error message",
  "details": {
    // Additional error-specific information
  }
}
```

As for any request, you will also receive a `x-correlation-id` response header that will help you find relevent activity events or application logs.

<CardGroup cols={2}>
  <Card title="code" icon="code">
    A machine-readable string identifier for the error type. Use this for programmatic error handling.
  </Card>

  <Card title="message" icon="message">
    A human-readable description of the error. The message may change over time, so don't rely on exact message matching.
  </Card>

  <Card title="details" icon="circle-info">
    An optional object containing additional information about the error, which varies based on the error type.
  </Card>

  <Card title="requestId" icon="fingerprint">
    A unique identifier for the request that can be provided to support for troubleshooting.
  </Card>
</CardGroup>

## HTTP Status Codes

<Tabs>
  <Tab title="2xx Success">
    | Code | Description                                               |
    | ---- | --------------------------------------------------------- |
    | 200  | OK - The request succeeded                                |
    | 201  | Created - A new resource was successfully created         |
    | 202  | Accepted - The request has been accepted for processing   |
    | 204  | No Content - The request succeeded but returns no content |
  </Tab>

  <Tab title="4xx Client Errors">
    | Code | Description                                                                     |
    | ---- | ------------------------------------------------------------------------------- |
    | 400  | Bad Request - The request contains invalid parameters or syntax                 |
    | 401  | Unauthorized - Authentication is required or has failed                         |
    | 403  | Forbidden - The authenticated user doesn't have sufficient permissions          |
    | 404  | Not Found - The requested resource does not exist                               |
    | 409  | Conflict - The request conflicts with the current state of the resource         |
    | 422  | Unprocessable Entity - The request was well-formed but contains semantic errors |
    | 429  | Too Many Requests - You've exceeded the rate limits                             |
  </Tab>

  <Tab title="5xx Server Errors">
    | Code | Description                                                            |
    | ---- | ---------------------------------------------------------------------- |
    | 500  | Internal Server Error - Something went wrong on our servers            |
    | 502  | Bad Gateway - A service required to fulfill the request is unavailable |
    | 503  | Service Unavailable - The server is temporarily unavailable            |
    | 504  | Gateway Timeout - A service required to fulfill the request timed out  |
  </Tab>
</Tabs>

## Common Error Codes

<Accordion title="Authentication Errors">
  | Code                  | HTTP Status | Description                                                 |
  | --------------------- | ----------- | ----------------------------------------------------------- |
  | `invalid_token`       | 401         | The provided token is invalid, expired, or has been revoked |
  | `missing_token`       | 401         | No authentication token was provided                        |
  | `invalid_credentials` | 401         | The provided username/password or API key is incorrect      |
  | `token_expired`       | 401         | The provided token has expired                              |
</Accordion>

<Accordion title="Authorization Errors">
  | Code                         | HTTP Status | Description                                                |
  | ---------------------------- | ----------- | ---------------------------------------------------------- |
  | `permission_denied`          | 403         | The authenticated user lacks the necessary permissions     |
  | `insufficient_scope`         | 403         | The token doesn't have the required scopes for this action |
  | `workspace_access_denied`    | 403         | The user doesn't have access to the specified workspace    |
  | `organization_access_denied` | 403         | The user doesn't have access to the specified organization |
</Accordion>

<Accordion title="Resource Errors">
  | Code                      | HTTP Status | Description                                                  |
  | ------------------------- | ----------- | ------------------------------------------------------------ |
  | `resource_not_found`      | 404         | The requested resource does not exist                        |
  | `resource_already_exists` | 409         | A resource with the specified identifier already exists      |
  | `resource_conflict`       | 409         | The request conflicts with the current state of the resource |
  | `resource_locked`         | 423         | The resource is currently locked and cannot be modified      |
</Accordion>

<Accordion title="Validation Errors">
  | Code                | HTTP Status | Description                                |
  | ------------------- | ----------- | ------------------------------------------ |
  | `invalid_request`   | 400         | The request body or parameters are invalid |
  | `invalid_parameter` | 400         | A specific parameter has an invalid value  |
  | `missing_parameter` | 400         | A required parameter is missing            |
  | `validation_failed` | 422         | The input failed validation checks         |
</Accordion>

<Accordion title="Rate Limiting Errors">
  | Code                       | HTTP Status | Description                                      |
  | -------------------------- | ----------- | ------------------------------------------------ |
  | `rate_limit_exceeded`      | 429         | You've exceeded the rate limit for this endpoint |
  | `quota_exceeded`           | 429         | You've exceeded your usage quota                 |
  | `concurrent_request_limit` | 429         | Too many concurrent requests                     |
</Accordion>

<Accordion title="Server Errors">
  | Code                  | HTTP Status | Description                                |
  | --------------------- | ----------- | ------------------------------------------ |
  | `internal_error`      | 500         | An unexpected error occurred on the server |
  | `service_unavailable` | 503         | The service is temporarily unavailable     |
  | `gateway_timeout`     | 504         | A dependent service timed out              |
  | `database_error`      | 500         | A database operation failed                |
</Accordion>

## Error Examples

<Tabs>
  <Tab title="Invalid Token">
    ```json theme={null}
    {
      "error": {
        "code": "invalid_token",
        "message": "The provided token is invalid or has expired",
        "requestId": "req-a1b2c3d4e5f6"
      }
    }
    ```
  </Tab>

  <Tab title="Resource Not Found">
    ```json theme={null}
    {
      "error": {
        "code": "resource_not_found",
        "message": "The requested workspace could not be found",
        "details": {
          "resourceType": "workspace",
          "resourceId": "ws-12345"
        },
        "requestId": "req-g7h8i9j0k1l2"
      }
    }
    ```
  </Tab>

  <Tab title="Validation Error">
    ```json theme={null}
    {
      "error": {
        "code": "validation_failed",
        "message": "The request contains invalid parameters",
        "details": {
          "errors": [
            {
              "field": "name",
              "message": "must be between 3 and 50 characters"
            },
            {
              "field": "description",
              "message": "cannot exceed 500 characters"
            }
          ]
        },
        "requestId": "req-m3n4o5p6q7r8"
      }
    }
    ```
  </Tab>

  <Tab title="Rate Limit Exceeded">
    ```json theme={null}
    {
      "error": {
        "code": "rate_limit_exceeded",
        "message": "Rate limit exceeded",
        "details": {
          "limit": 100,
          "period": "1m",
          "resetAt": "2025-04-06T12:30:00Z"
        },
        "requestId": "req-s9t0u1v2w3x4"
      }
    }
    ```
  </Tab>
</Tabs>

## Handling Errors

<Steps>
  <Step title="Check HTTP Status Code">
    First, check the HTTP status code to understand the general category of the error:

    ```javascript theme={null}
    if (response.status >= 400) {
      // Handle error based on status code
      if (response.status === 401) {
        // Authentication issue
      } else if (response.status === 403) {
        // Authorization issue
      } else if (response.status === 429) {
        // Rate limiting issue
      } else {
        // Other error
      }
    }
    ```
  </Step>

  <Step title="Parse Error Code">
    For more specific error handling, check the error code:

    ```javascript theme={null}
    if (response.data && response.data.error) {
      switch (response.data.error.code) {
        case 'token_expired':
          // Refresh the token
          break;
        case 'resource_not_found':
          // Handle missing resource
          break;
        case 'validation_failed':
          // Handle validation errors
          const validationErrors = response.data.error.details.errors;
          // Display validation errors to the user
          break;
        default:
          // Handle other errors
          break;
      }
    }
    ```
  </Step>

  <Step title="Implement Retry Logic">
    For certain errors, especially 429 (rate limiting) and some 5xx errors, implement retry logic with exponential backoff:

    ```javascript theme={null}
    async function apiCallWithRetry(url, options, maxRetries = 3) {
      let retries = 0;
      
      while (retries < maxRetries) {
        try {
          const response = await fetch(url, options);
          
          if (response.status === 429) {
            // Get retry after header if available
            const retryAfter = response.headers.get('Retry-After') || 1;
            const delay = parseInt(retryAfter, 10) * 1000;
            
            await new Promise(resolve => setTimeout(resolve, delay));
            retries++;
            continue;
          }
          
          if (response.status >= 500 && response.status < 600) {
            // Exponential backoff for server errors
            const delay = Math.pow(2, retries) * 1000 + Math.random() * 1000;
            await new Promise(resolve => setTimeout(resolve, delay));
            retries++;
            continue;
          }
          
          return response;
        } catch (error) {
          if (retries >= maxRetries - 1) {
            throw error;
          }
          
          // Exponential backoff for network errors
          const delay = Math.pow(2, retries) * 1000 + Math.random() * 1000;
          await new Promise(resolve => setTimeout(resolve, delay));
          retries++;
        }
      }
    }
    ```
  </Step>

  <Step title="Log Errors">
    Log errors with their requestId for troubleshooting:

    ```javascript theme={null}
    if (response.data && response.data.error) {
      console.error(
        `API Error: ${response.data.error.code} - ${response.data.error.message}`,
        `Request ID: ${response.data.error.requestId}`,
        response.data.error.details
      );
    }
    ```

    <Info>
      The requestId is particularly important when contacting support, as it allows for quick identification of the specific request in server logs.
    </Info>
  </Step>
</Steps>

## Best Practices

<CardGroup cols={2}>
  <Card title="Graceful Degradation" icon="spinner">
    Design your application to function (perhaps with limited capabilities) even when API requests fail.
  </Card>

  <Card title="User-Friendly Messages" icon="comment-dots">
    Translate error codes into user-friendly messages rather than displaying raw API errors to users.
  </Card>

  <Card title="Centralized Error Handling" icon="rectangle-list">
    Implement a centralized error handling mechanism to ensure consistent handling of errors across your application.
  </Card>

  <Card title="Contextual Recovery" icon="arrow-rotate-right">
    Provide context-specific recovery options based on the error type (e.g., refresh button, edit form, etc.).
  </Card>

  <Card title="Validation Precheck" icon="check-double">
    Validate inputs on the client side before sending requests to reduce validation errors.
  </Card>

  <Card title="Error Tracking" icon="chart-line">
    Implement error tracking to monitor error patterns and improve user experience over time.
  </Card>
</CardGroup>

## Troubleshooting Common Errors

<Accordion title="Authentication Failed">
  If you receive a 401 error:

  1. Check that your token is correctly formatted in the Authorization header
  2. Verify that your token hasn't expired
  3. Ensure you're using the correct authentication method for the endpoint
  4. Try generating a new token

  ```bash theme={null}
  # Example of correct token usage
  curl -X GET "https://api.studio.prisme.ai/v2/workspaces" \
       -H "Authorization: Bearer YOUR_TOKEN"
  ```
</Accordion>

<Accordion title="Permission Denied">
  If you receive a 403 error:

  1. Verify that the authenticated user has the necessary permissions
  2. Check if you're using an API key with limited scopes
  3. Ensure you're accessing resources within the correct workspace
  4. Check if the resource has additional access controls

  Common permission errors include attempting to access:

  * Resources in workspaces you're not a member of
  * Admin-only functionality without admin privileges
  * Resources owned by other users
</Accordion>

<Accordion title="Rate Limit Exceeded">
  If you receive a 429 error:

  1. Implement proper rate limit handling with backoff
  2. Check the `Retry-After` header for guidance on when to retry
  3. Optimize your code to batch requests where possible
  4. Consider upgrading your plan if you consistently hit limits

  See the [Rate Limits](/api-reference/rate-limits) page for more details on rate limiting.
</Accordion>

<Accordion title="Invalid Parameters">
  If you receive a 400 or 422 error:

  1. Check the `details` field in the error response for specific validation failures
  2. Verify that you're sending the correct data types
  3. Check for required fields that might be missing
  4. Ensure values are within acceptable ranges or formats

  ```json theme={null}
  // Example validation error details
  "details": {
    "errors": [
      {
        "field": "email",
        "message": "must be a valid email address"
      }
    ]
  }
  ```
</Accordion>

## Next Steps

<CardGroup cols={3}>
  <Card title="Rate Limits" icon="gauge-high" href="/api-reference/rate-limits">
    Learn about API usage limits and quotas
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Understand how to authenticate with the API
  </Card>

  <Card title="Security" icon="shield" href="/api-reference/security">
    Explore security best practices
  </Card>
</CardGroup>
