将WPF应用程序中未处理的异常记录到SQL数据库

时间:2017-08-01 18:22:05

标签: wpf logging

我正在使用VS2017的WPF应用程序。

关于使用C#在WPF中记录SQL Server数据库异常的最佳方法,我想提供一些建议吗?

我希望能够随时捕获任何异常。

2 个答案:

答案 0 :(得分:0)

看看这两个事件:

AppDomain.CurrentDomain.FirstChanceException
AppDomain.CurrentDomain.UnhandledException

您的代码可能如下所示:

public Form1()
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    InitializeComponent();
}

static void CurrentDomain_UnhandledException(object sender,     
{
    Exception eee = (Exception)e.ExceptionObject;
    MethodBase met = eee.TargetSite;
    MessageBox.Show("fatal error in method: " + met.Name
        + Environment.NewLine + eee.GetType().ToString() +
    Environment.NewLine + eee.Message, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    InsertIntoDatebase("insert into errors (datetime, error) values ('" + DateTime.Now.ToString() + "', '" + e.Message + "'");
    Environment.Exit(0);
}

void InsertIntoDatebase(string sql)
{
    // do it as usually, it depends what SQL database you use
}

答案 1 :(得分:0)

在我工作的WPF应用程序中,我们捕获了三个与异常相关的事件:

AppDomain.CurrentDomain.UnhandledException += (sender, args) => HandleException(args.ExceptionObject as Exception);
TaskScheduler.UnobservedTaskException += (sender, args) => HandleException(args.Exception);
DispatcherUnhandledException += (sender, args) => HandleException(args.Exception);

然而,我不是试图手动获取数据库连接并在事件处理程序中酝酿一些SQL,而是依赖于我知道可以很好地完成工作的第三方库。

我强烈建议您考虑配置log4net之类的解决方案及其ADO appenders的实施方案。您还可以设置日志记录到文件,轻松更改配置而无需重建应用程序,并提供日志记录到应用程序的其余部分。