Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter way to show error messages in async methods
    primarykey
    data
    text
    <p>The fact that we can't use the <code>await</code> keyword in <code>catch</code> blocks makes it quite awkward to show error messages from async methods in WinRT, since the <code>MessageDialog</code> API is asynchronous. Ideally I would like be able to write this:</p> <pre><code> private async Task DoSomethingAsync() { try { // Some code that can throw an exception ... } catch (Exception ex) { var dialog = new MessageDialog("Something went wrong!"); await dialog.ShowAsync(); } } </code></pre> <p>But instead I have to write it like this:</p> <pre><code> private async Task DoSomethingAsync() { bool error = false; try { // Some code that can throw an exception ... } catch (Exception ex) { error = true; } if (error) { var dialog = new MessageDialog("Something went wrong!"); await dialog.ShowAsync(); } } </code></pre> <p>All methods that need to do this have to follow a similar pattern, which I really don't like, because it reduces the code readability.</p> <p>Is there a better way to handle this?</p> <hr> <p><em>EDIT:</em> I came up with this (which is similar to what svick suggested in his comments):</p> <pre><code>static class Async { public static async Task Try(Func&lt;Task&gt; asyncAction) { await asyncAction(); } public static async Task Catch&lt;TException&gt;(this Task task, Func&lt;TException, Task&gt; handleExceptionAsync, bool rethrow = false) where TException : Exception { TException exception = null; try { await task; } catch (TException ex) { exception = ex; } if (exception != null) { await handleExceptionAsync(exception); if (rethrow) ExceptionDispatchInfo.Capture(exception).Throw(); } } } </code></pre> <p>Usage:</p> <pre><code>private async Task DoSomethingAsync() { await Async.Try(async () =&gt; { // Some code that can throw an exception ... }) .Catch&lt;Exception&gt;(async ex =&gt; { var dialog = new MessageDialog("Something went wrong!"); await dialog.ShowAsync(); }); } </code></pre> <p><code>.Catch&lt;...&gt;</code> calls can be chained to mimick multiple <code>catch</code> blocks.</p> <p>But I'm not really happy with this solution; the syntax is even more awkward than before...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload