Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
537 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...