Skip to content

error handling

Nagendra Dhanakeerthi edited this page Oct 30, 2024 · 1 revision

Error Handling Guide

Available Error Classes

ChatGPT::Error

Base error class for all gem-specific errors.

ChatGPT::APIError

Generic API error with status code and error type.

rescue ChatGPT::APIError => e
  puts e.message        # Error message
  puts e.status_code    # HTTP status code
  puts e.error_type     # Error type from API
end

ChatGPT::AuthenticationError

Raised for API key and authentication issues (401 errors).

ChatGPT::RateLimitError

Raised when hitting API rate limits (429 errors).

ChatGPT::InvalidRequestError

Raised for malformed requests or invalid parameters (400 errors).

Error Handling Examples

Basic Error Handling

begin
  response = client.chat(messages)
rescue ChatGPT::AuthenticationError => e
  # Handle auth errors
rescue ChatGPT::RateLimitError => e
  # Handle rate limits
rescue ChatGPT::InvalidRequestError => e
  # Handle invalid requests
rescue ChatGPT::APIError => e
  # Handle other API errors
end

Production Error Handling

def handle_chat_request(messages)
  client.chat(messages)
rescue ChatGPT::AuthenticationError => e
  Rails.logger.error "Authentication failed: #{e.message}"
  raise
rescue ChatGPT::RateLimitError => e
  Rails.logger.warn "Rate limit hit: #{e.message}"
  retry_with_backoff
rescue ChatGPT::InvalidRequestError => e
  Rails.logger.warn "Invalid request: #{e.message}"
  handle_invalid_request(e)
rescue ChatGPT::APIError => e
  Rails.logger.error "API error: #{e.message}"
  notify_error_tracking(e)
  raise
end

Best Practices

Retry Strategy

def retry_with_backoff(max_attempts = 3)
  attempts = 0
  begin
    attempts += 1
    yield
  rescue ChatGPT::RateLimitError => e
    if attempts < max_attempts
      sleep(2 ** attempts)
      retry
    else
      raise
    end
  end
end

Error Logging

def log_error(error)
  error_data = {
    message: error.message,
    status: error.status_code,
    type: error.error_type,
    backtrace: error.backtrace[0..5]
  }
  
  Rails.logger.error("ChatGPT Error: #{error_data.to_json}")
end