c# - WinRT C# : Cannot save UnhandledException to Storage

标签 c# winrt-xaml

我正在研究 WinRT。如果抛出未处理的异常,我想将消息文本写入存储。 我在“App.xaml.cs”中添加了一个事件处理程序,请参阅代码。

异常被捕获但是最后一行,也就是写入文件的地方,再次崩溃 -> 'exception'!

为什么?有什么想法吗?

 public App()
 {
    this.InitializeComponent();
    this.Suspending += OnSuspending;
    this.UnhandledException += App_UnhandledException;
 }

 async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
    StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder; 
    StorageFile file= await folder.CreateFileAsync("crash.log",CreationCollisionOption.OpenIfExists);

    await FileIO.AppendTextAsync(file, e.Message);  // <----- crash again -----
 }

谢谢

晴天

最佳答案

我一直在想同样的事情,并且在我的搜索中很早就偶然发现了这个。我找到了一种方法,希望这对其他人也有用。

问题是 await 正在返回对 UI 线程的控制,并且应用程序崩溃了。您需要延期,但没有真正的方法可以延期。

我的解决方案是改用设置存储。我假设大多数想要这样做的人都想做一些 LittleWatson 风格的事情,所以这里有一些代码修改自 http://blogs.msdn.com/b/andypennell/archive/2010/11/01/error-reporting-on-windows-phone-7.aspx为了您的方便:

namespace YourApp
{
    using Windows.Storage;
    using Windows.UI.Popups;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;

    public class LittleWatson
    {
        private const string settingname = "LittleWatsonDetails";
        private const string email = "mailto:?to=you@example.com&subject=YourApp auto-generated problem report&body=";
        private const string extra = "extra", message = "message", stacktrace = "stacktrace";

        internal static void ReportException(Exception ex, string extraData)
        {
            ApplicationData.Current.LocalSettings.CreateContainer(settingname, Windows.Storage.ApplicationDataCreateDisposition.Always);
            var exceptionValues = ApplicationData.Current.LocalSettings.Containers[settingname].Values;

            exceptionValues[extra] = extraData;
            exceptionValues[message] = ex.Message;
            exceptionValues[stacktrace] = ex.StackTrace;
        }

        internal async static Task CheckForPreviousException()
        {
            var container = ApplicationData.Current.LocalSettings.Containers;
            try
            {
                var exceptionValues = container[settingname].Values;
                string extraData = exceptionValues[extra] as string;
                string messageData = exceptionValues[message] as string;
                string stacktraceData = exceptionValues[stacktrace] as string;

                var sb = new StringBuilder();
                sb.AppendLine(extraData);
                sb.AppendLine(messageData);
                sb.AppendLine(stacktraceData);

                string contents = sb.ToString();

                SafeDeleteLog();

                if (stacktraceData != null && stacktraceData.Length > 0)
                {
                    var dialog = new MessageDialog("A problem occured the last time you ran this application. Would you like to report it so that we can fix the error?", "Error Report")
                    {
                        CancelCommandIndex = 1,
                        DefaultCommandIndex = 0
                    };

                    dialog.Commands.Add(new UICommand("Send", async delegate
                    {
                        var mailToSend = email.ToString();
                        mailToSend += contents;
                        var mailto = new Uri(mailToSend);
                        await Windows.System.Launcher.LaunchUriAsync(mailto);
                    }));
                    dialog.Commands.Add(new UICommand("Cancel"));

                    await dialog.ShowAsync();
                }
            }
            catch (KeyNotFoundException)
            {
                // KeyNotFoundException will fire if we've not ever had crash data. No worries!
            }
        }

        private static void SafeDeleteLog()
        {
            ApplicationData.Current.LocalSettings.CreateContainer(settingname, Windows.Storage.ApplicationDataCreateDisposition.Always);
            var exceptionValues = ApplicationData.Current.LocalSettings.Containers[settingname].Values;

            exceptionValues[extra] = string.Empty;
            exceptionValues[message] = string.Empty;
            exceptionValues[stacktrace] = string.Empty;
        }
    }
}

要实现它,您需要按照上面的链接执行相同的操作,但要确保数据在此处,以防 url 出现故障:

App.xaml.cs 构造函数(在调用 this.InitializeComponent() 之前):

this.UnhandledException += (s, e) => LittleWatson.ReportException(e.Exception, "extra message goes here");

显然,如果您已经有一个 UnhandledException 方法,您可以在其中调用 LittleWatson。

如果您使用的是 Windows 8.1,您也可以添加 NavigationFailed 调用。这需要在实际页面中(通常是 MainPage.xaml.cs 或任何首次打开的页面):

xx.xaml.cs 构造函数(任何给定页面):

rootFrame.NavigationFailed += (s, e) => LittleWatson.ReportException(e.Exception, "extra message goes here");

最后,您需要询问用户是否要在应用重新打开时发送电子邮件。在应用的默认页面构造函数中(默认:页面 App.xaml.cs 初始化):

this.Loaded += async (s, e) => await LittleWatson.CheckForPreviousException();

或者,如果您已经使用了 OnLoad 方法,则添加对它的调用。

关于c# - WinRT C# : Cannot save UnhandledException to Storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15000769/

相关文章:

c# - 根据 XmlEnumAttribute 名称值检索枚举值

c# - 您可以调用 Page.ClientScript.RegisterClientScriptBlock 的绝对最新时间是什么时候?

windows-8 - ScrollViewer 和处理子元素上的操作事件

c# - 如何在运行时更改列表框的数据模板方向?

xaml - 我应该如何在 Windows 应用商店应用程序中显示带有绑定(bind)数据的格式化文本?

c# - 无需大量转换即可创建和初始化不同的子类型

C# 动态对象创建/修改?

c# - 无法获取证书消息凭据以在我的 WCF 服务中工作

xaml - ScrollViewer 中是否可以有非滚动行?

c# - 如何在两个页面之间进行动画过渡?