Jeremy Thomas
Jeremy Thomas

Reputation: 6674

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 = @potential_client.name.split(" ").first || "N/A"
    @last_name = @potential_client.name.split(" ").last || "N/A"
    @phone = @potential_client.phone || "N/A"
    @email = @potential_client.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?
end

Upvotes: 1

Views: 437

Answers (1)

B Seven
B Seven

Reputation: 45943

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(Hubspot::RequestError.new(response)) unless response.success?

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

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

rescue Hubspot::RequestError
      # Handle an error here.
end

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

rescue Hubspot::RequestError
   return false
end

Then, you could use it with

if contact = createHubSpotContact(potential_client)
  ...
else
  #failure
end

Upvotes: 2

Related Questions