1

私はRails wrapper for the HubSpot APIを使用していますが、連絡先を正常に作成できてもエラーを処理できないようです。Rails 4:HubSpot APIエラーチェック

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 

答えて

2

bangメソッドcreate!は、連絡先が有効でない場合にエラーが発生するはずです。したがって、エラーを処理するためにcreateを通過することはありません。 create!方法は、ハブスポットのAPIを呼び出して、gem sourceを見てみると

:連絡先を作成する問題がある場合

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

raise(Hubspot::RequestError.new(response)) unless response.success? 

は、RequestErrorが発生します。だから、あなたはそれをキャッチすることができます:

rescue Hubspot::RequestError 
    return false 
end 

その後、あなたは

if contact = createHubSpotContact(potential_client) 
    ... 
else 
    #failure 
end 
でそれを使用することができます。これは createHubSpotContactからfalseを返すことであろう処理する

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

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

1つの方法