How to handle exceptions when creating contacts via HubSpot Ruby gem in Rails 4

I’m working with a HubSpot Ruby wrapper in my Rails 4 application. The contact creation works fine, but I’m struggling with proper error handling. When something goes wrong during the API call, my application doesn’t handle it gracefully.

def build_hubspot_user(client_data)
  puts "Building new hubspot user..."
  @client_data = client_data

  @given_name = @client_data.full_name.split(" ").first || "Unknown"
  @family_name = @client_data.full_name.split(" ").last || "Unknown"
  @contact_number = @client_data.phone_number || "N/A"
  @email_address = @client_data.email_address || "N/A"
  @source = @client_data.traffic_source || "direct"
  @location = Region.find(@client_data.region_id).title || "Unknown"
  @notes = @client_data.comments || "No message"

  new_contact = Hubspot::Contact.create!(@email_address, {
    firstname: @given_name,
    lastname: @family_name,
    phone: @contact_number,
    email: @email_address,
    source: @source,
    location: @location,
    notes: @notes
  })

  # How do I catch and manage errors at this point?
end

What’s the best way to handle API failures and exceptions in this scenario?

I ran into similar issues when integrating HubSpot with my Rails app last year. The main problem with your current code is that you’re using create! which will raise an exception immediately when something fails. I switched to using create instead and checking the response. You’ll want to wrap your API call in a begin-rescue block to catch network timeouts and authentication errors. Also consider that HubSpot rate limits can cause failures, so implementing a retry mechanism helped me a lot. I ended up creating a service class that returns a success/failure status along with any error messages, which made it much easier to handle in my controllers and provide meaningful feedback to users.