danesparza / MailChimp.NET

:envelope: .NET Wrapper for the MailChimp v2.0 API
MIT License
179 stars 119 forks source link

GetListsForEmail returns an exception if the email address is not subscribed to any lists #173

Closed williamsonjake closed 8 years ago

williamsonjake commented 8 years ago

hey there,

this maybe a misunderstanding on my part so apologies if this isn't a bug...

i've some unsubscribe code that check's if the email address is in the list before attempting to unsubscribe them:

var emailParameter = new EmailParameter
{
    Email = email
};

var lists = _mailChimpManager.GetListsForEmail(emailParameter);

if (!lists.Any()) return;

var isInList = lists.FirstOrDefault(x => x.Id == listId);

if (isInList != null) _mailChimpManager.Unsubscribe(listId, emailParameter);

calling 'GetListsForEmail' with an address that doesn't have any lists returns an exception:

The email address "blar@blar.com" is not subscribed to any lists.

am i going about this the wrong way? i guess in my head i was expecting an empty list to be returned rather than an exception...

whatcha reckon?!

cheers,

jake

danesparza commented 8 years ago

Great question, @williamsonjake ...

So it looks like the GetListsForEmail method calls the MailChimp API endpoint helper/lists-for-email.

Looking at their API docs, it looks like one of the errors this method could throw on the Mailchimp side is _ListNotSubscribed -- so yes -- I think this is normal.

williamsonjake commented 8 years ago

hi,

i did a bit more digging on this one as i wasn't 100% happy with wrapping the above code in a try/catch to suppress the 'List_NotSubscribed' exception...

based on other suggestions i found, this is what i've run with:

public UnsubscribeResult UnSubscribe(string listId, string email)
{
    var emailParameter = new EmailParameter
    {
        Email = email
    };

    var memberInfo = _mailChimpManager.GetMemberInfo(listId, new List<EmailParameter> { emailParameter });

    var member = memberInfo.Data.FirstOrDefault();

    if (member == null) return new UnsubscribeResult { Complete = true };

    if (member.Status == "unsubscribed") return new UnsubscribeResult { Complete = true };

    return _mailChimpManager.Unsubscribe(listId, emailParameter);
}

the code works on the basis that the 'UnsubscribeResult' status is true if the member can't be found or can be found but is already unsubscribed from the list.

if the member is found in the list the 'UnsubscribeResult' status is set by the unsubscribe method response.

feels a bit cleaner and get's rid of the try/catch!

i suppose a 'nice to have' would be to add a status code to the 'UnsubscribeResult' class so you can return different outcome messages to the user rather than a simple true/false?

cheers,

jake