Docs

API Error Handling Guide

This comprehensive guide outlines the error handling system for the Sentor ML API.

Error Response Format

All API errors follow a consistent JSON structure:

{
    "error": {
        "code": "string",
        "message": "string",
        "details": {},
        "request_id": "uuid",
        "timestamp": "ISO-8601 timestamp",
        "documentation_url": "https://docs.sentor.ml/errors/{code}"
    }
}

HTTP Status Codes

Status CodeTitleDescriptionExample
400Bad RequestInvalid input parametersMissing required field ‘text’
401UnauthorizedAuthentication failedInvalid or expired API key
403ForbiddenInsufficient permissionsPlan quota exceeded
404Not FoundResource doesn’t existInvalid endpoint or resource ID
422Unprocessable EntityValid syntax but semantically incorrectText too long (>5000 chars)
429Too Many RequestsRate limit exceededToo many requests per minute
500Internal Server ErrorServer-side errorUnexpected server error
503Service UnavailableTemporary server issueMaintenance mode active

Detailed Error Examples

Authentication Error

{
    "error": {
        "code": "auth_failed",
        "message": "Authentication failed",
        "details": {
            "reason": "expired_key",
            "expires_at": "2024-02-13T15:00:00Z"
        },
        "request_id": "req_abc123xyz",
        "timestamp": "2024-02-13T14:00:00Z",
        "documentation_url": "https://docs.sentor.ml/errors/auth_failed"
    }
}

Rate Limit Error

{
    "error": {
        "code": "rate_limit_exceeded",
        "message": "Too many requests",
        "details": {
            "rate_limit": {
                "limit": 60,
                "remaining": 0,
                "reset_at": "2024-02-13T14:05:00Z"
            }
        },
        "request_id": "req_def456uvw",
        "timestamp": "2024-02-13T14:00:00Z",
        "documentation_url": "https://docs.sentor.ml/errors/rate_limit_exceeded"
    }
}

Error Handling Best Practices

1. Implement Proper Error Handling

try:
    response = sentor.analyze_sentiment(text)
except SentorAPIError as e:
    if e.status_code == 429:
        # Implement exponential backoff
        time.sleep(e.details['rate_limit']['reset_at'])
    elif e.status_code == 400:
        # Log validation errors
        logger.error(f"Validation error: {e.details}")
    else:
        # Handle other errors
        logger.error(f"API error: {e.message}")

2. Rate Limit Handling

  • Implement exponential backoff
  • Monitor rate limit headers
  • Cache responses when appropriate
def exponential_backoff(retry_count):
    """Calculate wait time using exponential backoff."""
    return min(300, (2 ** retry_count) + random.uniform(0, 1))

3. Logging Best Practices

logger.error({
    'request_id': error.request_id,
    'status_code': error.status_code,
    'message': error.message,
    'timestamp': error.timestamp,
    'endpoint': error.endpoint
})

Response Headers

HeaderDescription
X-Request-IDUnique request identifier
X-RateLimit-LimitRate limit ceiling
X-RateLimit-RemainingRemaining requests
X-RateLimit-ResetRate limit reset timestamp

Support Resources

Language-Specific Error Handling

Python SDK

from sentor.exceptions import SentorAPIError

try:
    result = client.analyze("Sample text")
except SentorAPIError as e:
    print(f"Error {e.code}: {e.message}")
    print(f"Request ID: {e.request_id}")

JavaScript SDK

try {
    const result = await sentor.analyze("Sample text");
} catch (error) {
    if (error instanceof SentorAPIError) {
        console.error(`Error ${error.code}: ${error.message}`);
        console.error(`Request ID: ${error.requestId}`);
    }
}