ruby-on-railsmailchimpgibbon

Check if member exists using Mailchimp 3.0 API and Gibbon [rails]


I am using mailchimp API 3.0 to check if an email address is on a mailing list. I am using the Gibbon gem and if the email IS on the list my code works fine.

list_id = ENV['MAILCHIMP_LIST_ID']
@gibbon = Gibbon::Request.new(api_key: ENV['mailchimp_api_key'], symbolize_keys: true)
@member_id = Digest::MD5.hexdigest(params[:user_Email]
@member_info = @gibbon.lists(list_id).members(@member_id).retrieve.body[:status]
 => "subscribed"

However, if the email is NOT part of the list I get

@member_id_2 = "emailnot@inlist.net"

@member_info = @gibbon.lists(list_id).members(@member_id_2).retrieve.body[:status]
Gibbon::MailChimpError: the server responded with status 404 
@title="Resource Not Found", @detail="The requested resource could not 
be found.", @body{:type=>"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/", :title=>"Resource Not Found", :status=>404, :detail=>"The requested resource could not be found.", :instance=>"XXXXXXX4a76-ae0e-35406fc75c3f"}, @raw_body="{\"type\":\"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/\",\"title\":\"Resource Not Found\",\"status\":404,\"detail\":\"The requested resource could not be found.\",\"instance\":\"XXXXXXXX07c9-4a76-ae0e-35406fc75c3f\"}", @status_code=404

How can I have my code check if the email exists? Can I write an if else that looks for a 404 response?

    if @member_info == "subscribed" (member is present)
      @gibbon.lists(list_id).members(@member_id).update(body: {interests: {'interest_group': true}})
    else
      @gibbon.lists(list_id).members.create(body: { email_address: params[user_Email], status: 'subscribed', double_optin: false, interests: {'interest_group': true}})
    end

The 404 error causes my app to crash and it never creates the new subscriber


Solution

  • I got it!

    I used a begin/rescue to rescue the method and complete the steps.

     list_id = ENV['MAILCHIMP_LIST_ID']
     gibbon = Gibbon::Request.new(api_key: ENV['mailchimp_api_key'], symbolize_keys: true)
      member_id = Digest::MD5.hexdigest(params[:userEmail])
    begin
     member_info = gibbon.lists(list_id).members(member_id).retrieve.body[:status]
     gibbon.lists(list_id).members(member_id).update(body: {interests: {'interest_id': true}})
    
    rescue
     gibbon.lists(list_id).members.create(body: { email_address: params[:userEmail], status: 'subscribed', double_optin: false, interests: {'interest_id': true}})
    end
    
    redirect_to root_path, :notice => "Congrats!