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

# Error Handling

> Learn how to handle errors when using the FaceSign API.

The FaceSign API uses conventional HTTP response codes to indicate the success or failure of an API request. Understanding these errors and implementing proper error handling is crucial for building a robust integration.

## HTTP status codes

FaceSign returns the following HTTP status codes:

| Status Code                   | Description                                                                                                                                                                                                                 |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **200 OK**                    | The request was successful.                                                                                                                                                                                                 |
| **201 Created**               | The resource was successfully created.                                                                                                                                                                                      |
| **400 Bad Request**           | The request was invalid or cannot be served. Check the error message for details.                                                                                                                                           |
| **401 Unauthorized**          | The request requires authentication or the API key is invalid.                                                                                                                                                              |
| **403 Forbidden**             | The API key doesn't have permissions to perform the request. **Note**: The Dev environment may return 403 instead of 401 for missing authentication headers. Production consistently returns 401 for authentication issues. |
| **404 Not Found**             | The requested resource doesn't exist.                                                                                                                                                                                       |
| **409 Conflict**              | The request conflicts with another request (perhaps using the same idempotency key).                                                                                                                                        |
| **429 Too Many Requests**     | Too many requests hit the API too quickly. We recommend implementing exponential backoff.                                                                                                                                   |
| **500 Internal Server Error** | Something went wrong on FaceSign's end. These are rare.                                                                                                                                                                     |

## Error response format

All error responses follow a consistent format:

```json title="Error response" wrap theme={null}
{
    "error": {
      "type": "validation_error",
      "message": "The 'clientReferenceId' field is required",
      "code": "parameter_missing"
    }
}
```

### Error object properties

| Property  | Type     | Description                                                                                                                            |
| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `type`    | `string` | The type of error returned. One of: `authentication_error`, `validation_error`, `not_found_error`, `rate_limit_error`, `server_error`. |
| `message` | `string` | A human-readable message providing more details about the error.                                                                       |
| `code`    | `string` | A short string uniquely identifying the specific error (e.g., `invalid_api_key`, `parameter_missing`).                                 |

## Error types

| Error Type             | Description                                      |
| ---------------------- | ------------------------------------------------ |
| `authentication_error` | Failure to properly authenticate in the request. |
| `validation_error`     | Invalid request or failed validation.            |
| `not_found_error`      | Requested resource doesn't exist.                |
| `rate_limit_error`     | Too many requests hit the API too quickly.       |
| `server_error`         | Internal server error.                           |

## Handling errors

Here's how to properly handle errors when using the FaceSign SDK:

<Tabs>
  <Tab title="JavaScript">
    ```javascript title="Error handling examples" wrap theme={null}
    import Client from '@facesignai/api'
    import { FSNodeType } from '@facesignai/api'

    const client = new Client({
      auth: 'sk_test_...'
    })

    try {
      const { session, clientSecret } = await client.session.create({
        clientReferenceId: 'user-123',
        metadata: { source: 'web-app' },
        flow: [
          { id: 'start', type: FSNodeType.START, outcome: 'end' },
          { id: 'end', type: FSNodeType.END }
        ]
      })

      console.log('Session created:', session.id)
    } catch (err) {
      // Parse error response from API
      try {
        const errorResponse = JSON.parse(err.message)
        const { type, message, code } = errorResponse.error

        if (type === 'validation_error') {
          console.error('Validation error:', message)
          console.error('Error code:', code)
        } else if (type === 'authentication_error') {
          console.error('Authentication failed. Check your API key.')
        } else if (type === 'rate_limit_error') {
          console.error('Rate limited:', message)
        } else {
          console.error('API error:', message)
        }
      } catch {
        // Handle non-JSON errors (network issues, etc.)
        console.error('Request failed:', err.message)
      }
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python title="Error handling examples" wrap theme={null}
    import json
    import facesignai

    client = facesignai.Client(
        auth='sk_test_...'
    )

    try:
        response = client.session.create(
            client_reference_id='user-123',
            metadata={'source': 'web-app'},
            flow= [
              {'id': 'start', 'type': 'start', 'outcome': 'end'},
              {'id': 'end', 'type': 'end'}
            ]
        )

        print(f"Session created: {response['session']['id']}")
    except Exception as err:
        # Parse error response
        try:
            error_response = json.loads(str(err))
            error = error_response.get('error', {})
            error_type = error.get('type')
            message = error.get('message')
            code = error.get('code')

            if error_type == 'validation_error':
                print(f"Validation error: {message} ({code})")
            elif error_type == 'authentication_error':
                print("Authentication failed. Check your API key.")
            elif error_type == 'rate_limit_error':
                print(f"Rate limited: {message}")
            else:
                print(f"API error: {message}")
        except (json.JSONDecodeError, KeyError):
            print(f"Request failed: {str(err)}")
    ```
  </Tab>
</Tabs>

## Common errors and solutions

### Authentication errors

```json title="Invalid API key" wrap theme={null}
{
    "error": {
      "type": "authentication_error",
      "message": "Invalid API key provided.",
      "code": "invalid_api_key"
    }
}
```

**Solution**: Check that you're using the correct API key and that it hasn't been revoked.

### Validation errors

```json title="Missing required parameter" wrap theme={null}
{
    "error": {
      "type": "validation_error",
      "message": "The 'clientReferenceId' field is required.",
      "code": "parameter_missing"
    }
}
```

**Solution**: Ensure all required parameters are included in your request. Check the error message for details about which field is invalid.

### Rate limit errors

```json title="Rate limit exceeded" wrap theme={null}
{
    "error": {
      "type": "rate_limit_error",
      "message": "Too many requests. Please retry after 60 seconds.",
      "code": "rate_limit_exceeded"
    }
}
```

**Solution**: Implement exponential backoff and respect the `Retry-After` header.

## Implementing retry logic

For transient errors like network issues and rate limiting, implement exponential backoff:

<Tabs>
  <Tab title="JavaScript">
    ```javascript title="Retry with exponential backoff" wrap theme={null}
    import Client from '@facesignai/api'
    import type { SessionSettings } from '@facesignai/api'

    async function createSessionWithRetry(
      client: Client,
      params: SessionSettings,
      maxRetries = 3
    ) {
      let lastError: Error | undefined

      for (let i = 0; i < maxRetries; i++) {
        try {
          return await client.session.create(params)
        } catch (err) {
          lastError = err as Error

          // Try to parse error response
          try {
            const errorResponse = JSON.parse(lastError.message)
            const errorType = errorResponse.error?.type

            // Don't retry validation or authentication errors
            if (errorType === 'validation_error' || errorType === 'authentication_error') {
              throw lastError
            }
          } catch {
            // If not JSON, continue with retry
          }

          // Calculate delay with exponential backoff (1s, 2s, 4s, ...)
          const delay = Math.min(1000 * Math.pow(2, i), 10000)
          await new Promise(resolve => setTimeout(resolve, delay))
        }
      }

      throw lastError
    }

    // Usage
    const { session } = await createSessionWithRetry(client, {
      clientReferenceId: 'user-123',
      metadata: {},
      flow: [...]
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python title="Retry with exponential backoff" wrap theme={null}
    import time
    import json
    import facesignai

    def create_session_with_retry(client, params, max_retries=3):
        last_error = None

        for i in range(max_retries):
            try:
                return client.session.create(**params)
            except Exception as err:
                last_error = err

                # Try to parse error response
                try:
                    error_response = json.loads(str(err))
                    error_type = error_response.get('error', {}).get('type')

                    # Don't retry validation or authentication errors
                    if (error_type in ['validation_error', 'authentication_error']):
                        raise
                except (json.JSONDecodeError, KeyError):
                    pass  # Continue with retry

                # Calculate delay with exponential backoff (1s, 2s, 4s, ...)
                delay = min(1 * (2 ** i), 10)
                time.sleep(delay)

        raise last_error

    # Usage
    client = facesignai.Client(auth='sk_test_...')
    response = create_session_with_retry(client, {
        'client_reference_id': 'user-123',
        'metadata': {},
        'flow': [...]
    })
    ```
  </Tab>
</Tabs>

## Best practices

* **Handle errors gracefully** - Don't let API errors crash your application
* **Log errors for debugging** - Save error messages and context for troubleshooting
* **Implement retry logic** - Use exponential backoff for transient errors
* **Respect rate limits** - Monitor your usage and implement proper throttling
* **Parse error responses** - Extract `type`, `message`, and `code` from error objects
* **Show user-friendly messages** - Don't expose technical error details to end users
* **Handle network failures** - Catch both API errors and network issues

## Getting help

<Note>
  **Need help with persistent errors?**

  * Check the [API status page](https://status.facesign.ai) for any ongoing issues
  * Review your request parameters against the API documentation
  * Contact support with the request ID from the error response
</Note>

## Next steps

<CardGroup cols={2}>
  <Card title="Quick Start" href="/docs/mcp#quickstart">
    Get started in 5 minutes
  </Card>

  <Card title="SDKs" href="/docs/reference/sdks">
    Official SDK documentation
  </Card>
</CardGroup>
