33

I have the following reoccurring try/catch pattern in my code. Using a try/catch block to handle any exceptions thrown when calling a method in orionProxy.

async private void doGetContacts()
{
    try {
        currentContacts = await orionProxy.GetContacts (); // call method in orionProxy
        ShowContacts (); // do something after task is complete
    }
    catch (Exception e) {
        orionProxy.HandleException (e); // handle thrown exception
    }
}

What I would like to write is something like the following.

async private void doGetContacts()
{
    currentContacts = await orionProxy.CheckForException(orionProxy.GetContacts ());
    ShowContacts (); // do something after task is complete but shouldn't run on exception
}

Any pointers/suggestions? I've tried various forms of Actions/Tasks/Lambdas but nothing will properly trap the exception in orionProxy.CheckForException(?) so ShowContacts doesn't run.

svick
  • 236,525
  • 50
  • 385
  • 514
user1231595
  • 425
  • 1
  • 4
  • 7
  • Tasks will throw an `AggregateException`. Is that what you're trying to catch? Or are you trying to catch a specific exception? – Simon Whitehead Oct 02 '13 at 23:37

1 Answers1

53

I don't see why it wouldn't work, assuming GetContacts is an async method:

public async Task<T> CheckForExceptionAsync<T>(Task<T> source)
{
  try
  {
    return await source;
  }
  catch (Exception ex)
  {
    HandleException(ex);
    return default(T);
  }
}

On a side note, you should avoid async void (as I describe in my MSDN article) and end your async method names with the Async suffix.

Philippe
  • 4,088
  • 4
  • 44
  • 49
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thanks, this worked. I still need to check if result = null (if (currentContacts != null) ShowContacts();) but the pattern is clean. – user1231595 Oct 03 '13 at 17:30
  • If I call your above method `await CheckForExceptionAsync` it throws an aggregate exception in code rather than trapping it. Is that how it's supposed to work? – The Muffin Man Jan 21 '15 at 17:16
  • 1
    @TheMuffinMan: Not unless `HandleException` throws an `AggregateException`. If you have a reproducible case, feel free to post it as a question. – Stephen Cleary Jan 21 '15 at 18:05
  • I think it was an outside issue in my code. Thanks for the reply. – The Muffin Man Jan 21 '15 at 18:17