locked
How to show error message In Async Function

    Question

  • Originally, I used private async void for the Control GridView's Item Click. When I changed it to private async Task

    I got error Msg :

    ItemsGridView_ItemClick(object, Windows.UI.Xaml.Controls.ItemClickEventArgs)' has the wrong return type


    What I wanted:
    - to show whatever error message in Try-catch in MessageDialog and exit

     

     private async Task ItemsGridView_ItemClick(object sender, ItemClickEventArgs e)
     {

           bool ShowError = false;
           System.Exception MyException = new Exception();

           try
          {

             -- call Async Method --

           }
         catch (Exception ex)
           {
               ShowError = true;
               MyException = ex;
            }
           if (ShowError)
           {
               var MyMessageBox = new Windows.UI.Popups.MessageDialog(MyException.Message,"Selecting Item");
               await MyMessageBox.ShowAsync();
           }

    }

    Tuesday, February 11, 2014 5:32 AM

Answers

  • Showing error messages in MessageDialogs is generally a bad interface. Displaying the error inline or in a popup is usually much more friendly. See Choosing the right UI surfaces: Errors

    For your specific flow here remove the "Task" return from the Click event handler. You need to return the Task if you want to await the function, not if you want to call await inside it. Since event handlers aren't awaited they shouldn't return Tasks. If you want to call the same code from elsewhere then factor it out of the event handler.

    --Rob

    Tuesday, February 11, 2014 6:30 AM
    Owner