FaceSign
Reference

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 CodeDescription
200 OKThe request was successful.
201 CreatedThe resource was successfully created.
400 Bad RequestThe request was invalid or cannot be served. Check the error message for details.
401 UnauthorizedThe request requires authentication or the API key is invalid.
403 ForbiddenThe 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 FoundThe requested resource doesn't exist.
409 ConflictThe request conflicts with another request (perhaps using the same idempotency key).
429 Too Many RequestsToo many requests hit the API too quickly. We recommend implementing exponential backoff.
500 Internal Server ErrorSomething went wrong on FaceSign's end. These are rare.

Error response format

All error responses follow a consistent format:

Error response
{
    "error": {
      "type": "validation_error",
      "message": "The 'clientReferenceId' field is required",
      "code": "parameter_missing"
    }
}

Error object properties

PropertyTypeDescription
typestringThe type of error returned. One of: authentication_error, validation_error, not_found_error, rate_limit_error, server_error.
messagestringA human-readable message providing more details about the error.
codestringA short string uniquely identifying the specific error (e.g., invalid_api_key, parameter_missing).

Error types

Error TypeDescription
authentication_errorFailure to properly authenticate in the request.
validation_errorInvalid request or failed validation.
not_found_errorRequested resource doesn't exist.
rate_limit_errorToo many requests hit the API too quickly.
server_errorInternal server error.

Handling errors

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

Error handling examples
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)
  }
}
Error handling examples
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)}")

Common errors and solutions

Authentication errors

Invalid API key
{
    "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

Missing required parameter
{
    "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

Rate limit exceeded
{
    "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:

Retry with exponential backoff
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: [...]
})
Retry with exponential backoff
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': [...]
})

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

Next steps

On this page