记录未处理的异常

时间:2014-01-30 02:35:25

标签: c# .net wpf exception

我一直试图将此异常记录几天,但无法弄明白。所以我想我在这里发布,希望有人可以提供帮助。我还发布了一些我正在使用的代码来捕获未处理的异常,但异常从未出现在日志文件中。

如果有人可以帮助我,我将不胜感激。

  

问题事件名称:APPCRASH
    应用程序名称:Myapp.exe
    应用版本:1.0.0.0
    申请时间戳:52e9aab8
    故障模块名称:clr.dll
    故障模块版本:4.0.30319.18052
    故障模块时间戳:5173c26b
    例外代码:c00000fd
    异常抵消:00372b52
    操作系统版本:6.1.7601.2.1.0.272.7
    地区ID:1033
    附加信息1:5cff
    附加信息2:5cfff2c5825852a6f100872ec6f038a2
    附加信息3:a2a3
    附加信息4:a2a3734c473189c5efabc88b5081d05a

public MainWindow()
{
    Application.Current.DispatcherUnhandledException += CurrentOnDispatcherUnhandledException;
    AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    Dispatcher.UnhandledException += DispatcherOnUnhandledException;
    InitializeComponent();          
}

private void DispatcherOnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
{
    Exception e = (Exception)args.Exception;
    using (StreamWriter writer = File.AppendText("ExceptionsLog.txt"))
    {
        DateTime time = DateTime.Now;
        writer.WriteLine("Time {0} Exception: {1}", time, e);
        writer.Flush();
    }
    args.Handled = true;
    MessageBox.Show(e.ToString());
}

private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
    Exception e = (Exception)args.ExceptionObject;
    using (StreamWriter writer = File.AppendText("ExceptionsLog.txt"))
    {
        DateTime time = DateTime.Now;
        writer.WriteLine("Time {0} Exception: {1} Runtime termination: {2}", time, e.Message, args.IsTerminating);
        writer.Flush();
    }
    MessageBox.Show(e.ToString());
}

private void CurrentOnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
{
    Exception e = (Exception)args.Exception;
    using (StreamWriter writer = File.AppendText("ExceptionsLog.txt"))
    {
        DateTime time = DateTime.Now;
        writer.WriteLine("Time {0} Exception: {1}", time, e);
        writer.Flush();
    }
    args.Handled = true;
    MessageBox.Show(e.ToString());
}

1 个答案:

答案 0 :(得分:-1)

要处理未处理的异常,请创建一个这样的方法

   protected TResult LogFailedOperations<TResult>(Func<TResult> action)
        {
            try
            {
                return action();
            }
            catch (Exception ex)
            {
                // Logic for logging from ex.Message
            }
        }

此外,当您执行任何方法时,只需将此方法包含在此LogFailedOperations方法中,就像这些示例一样 -

private void MyButton_Click(object sender, RoutedEventArgs e)
{
  var result = LogFailedOperations(() => { /* Your logic for button click */ });
}

private void LoadDataToView()
{
  var result = LogFailedOperations(() => { /* Your logic for laoding data */ });
}

private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
  var result = LogFailedOperations(() => { /* Your logic for slider changed event */ });
}