AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
错误触发事件
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string str = FormaterExceptionMsg(e.ExceptionObject as Exception, e.ToString()); // FormaterExceptionMsg
//这个是自己写方法处理异常字符串信息
File.AppendAllText("StackErr.log", str);
}
网上社区比较火的格式:
static string FormaterExceptionMsg(Exception ex, string backStr)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("****************************异常文本****************************");
sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
if (ex != null)
{
sb.AppendLine("【异常类型】:" + ex.GetType().Name);
sb.AppendLine("【异常信息】:" + ex.Message);
sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
}
else
{
sb.AppendLine("【未处理异常】:" + backStr);
}
sb.AppendLine("***************************************************************");
sb.AppendLine();
return sb.ToString();
}```