Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async/await exception handling pattern

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.

like image 495
user1231595 Avatar asked Oct 02 '13 23:10

user1231595


People also ask

Does await throw error?

If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.

What is async await pattern?

In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function.

How do I get exceptions in await?

If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed. The calculation method traces the thrown exception automatically because I did use the ApiChange.


1 Answers

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.

like image 160
Stephen Cleary Avatar answered Oct 15 '22 14:10

Stephen Cleary