Browse Source

Added MessageDialog.ErrorIfFail

Kenric Nugteren 1 month ago
parent
commit
01be5e2534

+ 14 - 2
InABox.Avalonia/Components/MenuPanel/AvaloniaMenuItem.cs

@@ -2,7 +2,9 @@
 using Avalonia.Media;
 using CommunityToolkit.Mvvm.ComponentModel;
 using CommunityToolkit.Mvvm.Input;
+using InABox.Avalonia.Dialogs;
 using InABox.Core;
+using System.Runtime.CompilerServices;
 
 namespace InABox.Avalonia.Components;
 
@@ -89,7 +91,7 @@ public partial class AvaloniaMenuItem : ObservableObject
                         Header = item.Header,
                         Icon = new Image { Source = item.Image },
                         Command = item.Action != null
-                            ? new RelayCommand(() => item.Action())
+                            ? new RelayCommand(() => item.Action().ErrorIfFail())
                             : null
                     };
                     targetItems.Add(targetItem);
@@ -106,4 +108,14 @@ public partial class AvaloniaMenuItem : ObservableObject
                 targetItems.Add(targetItem);
             }
     }
-}
+}
+
+public static class AvaloniaMenuExtensions
+{
+    public static ContextMenu Build(this CoreMenu<IImage> menu)
+    {
+        var contextMenu = new ContextMenu();
+        AvaloniaMenuItem.LoadMenuItems(menu.Items, contextMenu.Items);
+        return contextMenu;
+    }
+}

+ 25 - 0
InABox.Avalonia/Dialogs/MessageDialog/MessageDialog.cs

@@ -35,4 +35,29 @@ public static class MessageDialog
     
     public static async Task<MessageDialogResult> ShowYesNoCancel(string message)
         => await MessageDialogViewModel.ShowYesNoCancel(message);
+
+    /// <summary>
+    /// When <paramref name="task"/> has finished, show a message dialog with the error if the task failed.
+    /// </summary>
+    /// <remarks>
+    /// Call this on the main thread. Use if spinning of a task that you don't care about the result, but don't want to fail silently.
+    /// </remarks>
+    /// <param name="task"></param>
+    /// <returns></returns>
+    public static Task ErrorIfFail(this Task task, bool shouldLog = true)
+    {
+        return task.ContinueWith(async t =>
+        {
+            if(t.Exception is AggregateException e && e.InnerException is not null)
+            {
+                MobileLogging.Log(e);
+                await ShowError(e.InnerException);
+            }
+            else if(t.Exception is not null)
+            {
+                MobileLogging.Log(t.Exception);
+                await ShowError(t.Exception);
+            }
+        }, TaskScheduler.FromCurrentSynchronizationContext());
+    }
 }