WPF中捕获全局异常并记录
应用有时候会异常崩溃,这时候如果有错误的堆栈信息,就很方便我们查找问题。捕获未处理异常我们只需要在App.xaml.cs
中写异常捕获逻辑即可。
public partial class App : Application
{
public App()
{
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
}
private void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("应用退出");
}
void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("我们很抱歉,当前应用程序遇到一些问题,该操作已经终止,请进行重试,如果问题继续存在,请联系管理员:" + e.Exception.Message, "意外的操作", MessageBoxButton.OK, MessageBoxImage.Information);//这里通常需要给用户一些较为友好的提示,并且后续可能的操作
e.Handled = true;//使用这一行代码告诉运行时,该异常被处理了,不再作为UnhandledException抛出了。
ApplicationHelper.Log(e.Exception);
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("我们很抱歉,当前应用程序遇到一些问题,该操作已经终止,请进行重试,如果问题继续存在,请联系管理员:" + e.ToString(), "意外的操作", MessageBoxButton.OK, MessageBoxImage.Information);
ApplicationHelper.Log(e);
}
}
贴一个我平时使用的代码:
static class ApplicationHelper
{
/// <summary>
/// 错误记录路径
/// </summary>
private static string LogPath = Path.Combine(ApplicationHelper.GetAppDefaultPath(), "Log.txt");
/// <summary>
/// 应用默认数据路径
/// </summary>
/// <returns></returns>
public static string GetAppDefaultPath()
{
var path = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Data", "Default");
DirectoryInfo directory = new DirectoryInfo(path);
if (directory.Exists)
{
return path;
}
else
{
directory.Create();
}
return path;
}
/// <summary>
/// 应用产生的数据
/// </summary>
/// <returns></returns>
public static string GetAppDataPath()
{
var path = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Data");
DirectoryInfo directory = new DirectoryInfo(path);
if (directory.Exists)
{
return path;
}
else
{
directory.Create();
}
return path;
}
/// <summary>
/// 记录未捕获异常信息
/// </summary>
/// <param name="e"></param>
public static void Log(UnhandledExceptionEventArgs e)
{
Log(e.ToString());
}
/// <summary>
/// 记录异常
/// </summary>
/// <param name="e"></param>
public static void Log(Exception e)
{
Log(e.ToString());
}
/// <summary>
/// 记录模板。也可用于直接调用,记录一些信息
/// </summary>
/// <param name="error"></param>
public static void Log(string error)
{
var sb = new StringBuilder();
sb.AppendLine("*****************************************");
sb.AppendLine(string.Format("{0} {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()));
sb.AppendLine("");
sb.AppendLine(error);
sb.AppendLine("*****************************************");
sb.AppendLine("");
sb.AppendLine("");
File.AppendAllText(LogPath, sb.ToString());
}
}
网友评论