Jeremy Thomas Jeremy Thomas - 3 months ago 58
Ruby Question

Rails 4: HubSpot API error checking

I am using the Rails wrapper for the HubSpot API and while I am able to successfully create contacts, I cannot seem to handle errors.

def createHubSpotContact(potential_client)
puts "creating hubspot contact..."
@potential_client = potential_client

@first_name =" ").first || "N/A"
@last_name =" ").last || "N/A"
@phone = || "N/A"
@email = || "N/A"
@referrer = @potential_client.referrer || "other"
@city = Location.find(@potential_client.location_id).name || "N/A"
@message = @potential_client.message || "N/A"

contact = Hubspot::Contact.create!(@email, {
firstname: @first_name,
lastname: @last_name,
phone: @phone,
email: @email,
referrer: @referrer,
city: @city,
message: @message

# What can I do to handle an error here?


The bang method create! should raise an error if the contact is not valid. Therefore, you would never get past the create to handle the error.

Taking a look at the gem source, the create! method calls the HubSpot API:

response = Hubspot::Connection.post_json(CREATE_CONTACT_PATH, params: {}, body: post_data )

In Connection#post_json,

raise( unless response.success?

If there is a problem creating the contact, a RequestError is raised. So, you can catch that:

  contact = Hubspot::Contact.create!(@email, {

rescue Hubspot::RequestError
      # Handle an error here.

One way to handle this would be to return false from createHubSpotContact:

rescue Hubspot::RequestError
   return false

Then, you could use it with

if contact = createHubSpotContact(potential_client)