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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With