Reputation: 391
I am trying to use a button on a webform to process adding a user to mail chimp. I have two functions... a button function that calls the async function that calls out to the API.
public class MailChimpResponse
{
public bool IsSuccessful;
public string ReponseMessage;
}
public void SubscribeEmail(object Sender, EventArgs e)
{
var mcResponse = SubscribeEmailAsync();
var result = mcResponse.Result;
if (result.IsSuccessful == true)
{
lblSuccess.Text = result.ReponseMessage;
pnlSuccess.Visible = true;
}
else
{
lblError.Text = result.ReponseMessage;
pnlError.Visible = false;
}
}
public async Task<MailChimpResponse> SubscribeEmailAsync()
{
IMailChimpManager mailChimpManager = new MailChimpManager(ConfigurationManager.AppSettings["testing"]);
MailChimpResponse mcResponse = new MailChimpResponse();
var listId = "xxxxxxxxx";
return await Task.Run(() =>
{
try
{
var mailChimpListCollection = mailChimpManager.Members.GetAllAsync(listId).ConfigureAwait(false);
mcResponse.IsSuccessful = true;
mcResponse.ReponseMessage = "Success!";
}
catch (AggregateException ae)
{
mcResponse.IsSuccessful = false;
mcResponse.ReponseMessage = ae.Message.ToString();
}
return mcResponse;
});
Currently the line filling the "var mailChimpListCollection" SHOULD FAIL throwing back an exception (and I can see it through Intellisense) however it continues on with the TRY rather than falling into the CATCH. This just makes every call appear to be successful, even if it is not. What am I missing here?
Upvotes: 3
Views: 1693
Reputation: 2887
According to your description, you're trying to return the response from the SubscribeEmailAsync
method, based on the outcome of the mailChimpManager.Members.GetAllAsync(listId)
call.
As the GetAllAsync
method is an async method, rather than returning the members list, it returns a task tracking the results retrieval work. You're really missing an await there and you don't need the artificial Task.Run
at all. Here how I'd rewrite SubscribeEmailAsync
method:
public async Task<MailChimpResponse> SubscribeEmailAsync()
{
IMailChimpManager mailChimpManager = new MailChimpManager(ConfigurationManager.AppSettings["testing"]);
MailChimpResponse mcResponse = new MailChimpResponse();
var listId = "xxxxxxxxx";
try
{
var mailChimpListCollection = await mailChimpManager.Members.GetAllAsync(listId).ConfigureAwait(false);
mcResponse.IsSuccessful = true;
mcResponse.ReponseMessage = "Success!";
}
catch (AggregateException ae)
{
mcResponse.IsSuccessful = false;
mcResponse.ReponseMessage = ae.Message.ToString();
}
return mcResponse;
}
Hope this helps.
Upvotes: 4