- Notifications
You must be signed in to change notification settings - Fork 6
error handling
Nagendra Dhanakeerthi edited this page Oct 30, 2024 · 1 revision
Base error class for all gem-specific errors.
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
Raised for API key and authentication issues (401 errors).
Raised when hitting API rate limits (429 errors).
Raised for malformed requests or invalid parameters (400 errors).
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
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
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
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