c# - 如何在 FirstChanceException 的日志记录中包含实际的表单类名?
问题描述
我的情况如下:
- 我有一个表格
FormBase
- 从此继承
FormBaseList
_FormBaseDetail
现在在我的主窗体上,我想从 FirstChanceException 事件中记录一些异常。我记录Exception.Message
了完整的stacktrace
但是在stacktrace
我有一个问题。
例如,我创建了一个表单FormCustomerDetail
,它的派生自FormBaseDetail
.
并且在定义的受保护或私有方法中发生异常,FormBaseDetail
然后堆栈跟踪将显示FormBaseDetail
而不是FormCustomerDetail
这对我来说是个问题,因为现在我不知道异常发生的实际形式。大约有 50 种形式来源于FormBaseDetail
所以问题是,有没有办法在FirstChanceException
事件中检索实际表单的类名?还是名字?
AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
private void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
StackTrace stackTraceObject = new StackTrace();
string stackTrace = stackTraceObject.ToString();
// I need to retrieve the actual form name or classname here...
LogError(
//ActualFormName + Environment.NewLine +
e.Exception.GetType().FullName + Environment.NewLine +
e.Exception.Message + Environment.NewLine +
stackTrace);
}
日志条目示例:
System.FormatException
Cannot convert xx to type boolean...
...
at Test_app.FormBaseDetail.OpenTables()
at Test_app.FormBaseDetail.PrepareFormLoad()
...
我想得到什么
Exeption occured in FormCustomerDetail
System.FormatException
Cannot convert xx to type boolean...
...
at Test_app.FormBaseDetail.OpenTables()
at Test_app.FormBaseDetail.PrepareFormLoad()
...
解决方案
天真的方法是将其实际记录在基本表单中 - 即有类似的东西:
class FormBaseDetail
{
private void Guard(Action a)
{
try { a.Invoke(); }
catch(Exception e)
{
throw new Exception("Exception on '" + this.GetType() + "'", e);
}
}
// pretty much everywhere in base class
public void PrepareFormLoad()
{
Guard(() => { ... });
}
}
此外,我可以想象挂钩FormLoad
并将 Form 的活动类型放入一些静态变量中。