Error Handling

Error Handling Guide

Comprehensive guide to handling SearchHive API errors gracefully in your applications. Learn about error codes, retry strategies, and best practices.

Error Response Format
All SearchHive API errors return consistent JSON responses with error codes, descriptions, and actionable details to help you debug issues quickly.

Error Response Structure

All error responses follow a consistent format to make error handling predictable:

Standard Error Response Format

JSON
{
  "error": "Rate limit exceeded",
  "code": "RATE_LIMITED",
  "details": "You have exceeded the rate limit for your plan. Please wait before making more requests.",
  "retry_after": 60,
  "request_id": "req_1234567890",
  "timestamp": "2025-01-15T10:30:00Z",
  "documentation_url": "https://docs.searchhive.dev/errors"
}

Response Fields

error - Human-readable error message
code - Machine-readable error code
details - Additional context and guidance
request_id - Unique identifier for debugging

Optional Fields

retry_after - Seconds to wait before retry
remaining - Requests/credits remaining
reset - When limits reset (Unix timestamp)
validation_errors - Field-specific errors

HTTP Status Codes

400 Bad Request

The request was invalid or cannot be served

Common Causes:

  • Missing required parameters
  • Invalid parameter values
  • Malformed JSON body
  • Invalid query syntax

Example Response:

{ "error": "Missing required parameter: query", "code": "MISSING_PARAMETER", "details": "The 'query' parameter is required for search requests" }
401 Unauthorized

Authentication failed or API key is invalid

Common Causes:

  • Missing Authorization header
  • Invalid API key format
  • Expired API key
  • API key not found

Example Response:

{ "error": "Invalid API key", "code": "AUTHENTICATION_FAILED", "details": "Please check your API key and ensure it's correctly formatted" }
402 Payment Required

Account has insufficient credits or billing issue

Common Causes:

  • Credits exhausted
  • Payment method failed
  • Account suspended
  • Plan limit exceeded

Example Response:

{ "error": "Insufficient credits", "code": "NO_CREDITS", "credits_remaining": 0, "details": "Your account has no remaining credits. Please upgrade your plan." }
429 Too Many Requests

Rate limit exceeded for your plan tier

Common Causes:

  • Exceeded requests per minute
  • Concurrent request limit
  • Burst limit exceeded
  • Daily/monthly limit reached

Example Response:

{ "error": "Rate limit exceeded", "code": "RATE_LIMITED", "retry_after": 60, "limit": 100, "remaining": 0, "reset": 1640995200 }
500 Internal Server Error

Unexpected server error occurred

Common Causes:

  • Database connection issues
  • Service temporarily unavailable
  • Unexpected system error
  • Third-party service failure

Example Response:

{ "error": "Internal server error", "code": "INTERNAL_ERROR", "details": "An unexpected error occurred. Please try again later.", "request_id": "req_1234567890" }

Validation Errors (400)

When request parameters are invalid, you'll receive detailed validation errors:

FieldErrorSolution
queryQuery parameter is requiredProvide a non-empty query string
max_resultsmax_results must be between 1 and 100Set max_results to a value between 1-100
urlInvalid URL formatEnsure URL includes protocol (http/https)
extract_optionsInvalid extraction optionUse valid options: title, text, links, images, metadata

Implementation Examples

Robust error handling with retry logic, exponential backoff, and proper exception handling:

Comprehensive Error Handling

#!/bin/bash

# SearchHive API error handling script
API_KEY="sk_live_your_key_here"
BASE_URL="https://www.searchhive.dev/api/v1"
MAX_RETRIES=3

make_api_request() {
    local endpoint="$1"
    local data="$2"
    local attempt=1
    
    while [ $attempt -le $MAX_RETRIES ]; do
        echo "Attempt $attempt of $MAX_RETRIES"
        
        # Make the request and capture response + status code
        response=$(curl -s -w "%{json}%{http_code}" \
            -X POST "$BASE_URL/$endpoint" \
            -H "Authorization: Bearer $API_KEY" \
            -H "Content-Type: application/json" \
            -d "$data" \
            --max-time 30)
        
        # Extract status code (last 3 characters)
        http_code="${response: -3}"
        # Extract response body (everything except last 3 characters)
        response_body="${response%???}"
        
        case $http_code in
            200)
                echo "✅ Success!"
                echo "$response_body" | jq '.'
                return 0
                ;;
            400)
                echo "❌ Bad Request (400)"
                echo "$response_body" | jq -r '.error // "Invalid request parameters"'
                return 1
                ;;
            401)
                echo "🔒 Unauthorized (401)"
                echo "Please check your API key"
                return 1
                ;;
            402)
                echo "💳 Payment Required (402)"
                echo "Insufficient credits - please upgrade your plan"
                return 1
                ;;
            429)
                echo "⏰ Rate Limited (429)"
                retry_after=$(echo "$response_body" | jq -r '.retry_after // 60')
                if [ $attempt -lt $MAX_RETRIES ]; then
                    echo "Waiting $retry_after seconds before retry..."
                    sleep "$retry_after"
                    attempt=$((attempt + 1))
                    continue
                else
                    echo "Max retries exceeded"
                    return 1
                fi
                ;;
            5*)
                echo "🔧 Server Error ($http_code)"
                if [ $attempt -lt $MAX_RETRIES ]; then
                    wait_time=$((2 ** (attempt - 1)))
                    echo "Retrying in $wait_time seconds..."
                    sleep $wait_time
                    attempt=$((attempt + 1))
                    continue
                else
                    echo "Server error persists after $MAX_RETRIES attempts"
                    return 1
                fi
                ;;
            000)
                echo "🌐 Network Error"
                if [ $attempt -lt $MAX_RETRIES ]; then
                    echo "Connection failed, retrying..."
                    attempt=$((attempt + 1))
                    continue
                else
                    echo "Network error persists"
                    return 1
                fi
                ;;
            *)
                echo "❓ Unexpected Status ($http_code)"
                echo "$response_body"
                return 1
                ;;
        esac
    done
}

# Example usage
echo "Testing SwiftSearch API..."
make_api_request "swiftsearch" '{
    "query": "latest news",
    "max_results": 5
}'

Error Handling Best Practices

Do's
Always check status codes before processing responses
Implement exponential backoff for retries
Log error details with request IDs
Handle network timeouts gracefully
Provide meaningful error messages to users
Don'ts
Don't ignore error responses
Don't retry immediately without delays
Don't expose API keys in error logs
Don't retry on 4xx errors (except 429)
Don't fail silently - always handle errors

Monitoring & Debugging

Error Monitoring

Track error patterns to identify issues:

  • • Monitor error rates and types
  • • Set up alerts for unusual patterns
  • • Track retry success rates
  • • Monitor credit usage trends
Debugging Tips

Debug issues effectively:

  • • Always log the request_id
  • • Include full error response in logs
  • • Test with curl for isolated debugging
  • • Check API status page for outages

Still Having Issues?

If you're encountering persistent errors or need help with implementation, our support team is here to help.

Include in Support Requests:
• Request ID from error response
• Full error message and status code
• Your implementation code (sanitized)
• Expected vs actual behavior