c# – 在Application_UnhandledException事件中从StatckTrace获取Method,Class和LineNumber

我正在开发Windows Phone 7 Silverlight应用程序.我想进行应用程序级错误处理,而不是在所有方法中编写try … catch …我需要提取实际错误发生的方法名称,类名称和行号.以下是演示代码.在Application_UnhandledException事件中,我期待Method =“GenerateError”和Class =“ExceptionTesting”.另外,我想让LineNumber发生实际错误(代码中没有显示).

生成错误的代码:

public partial class ExceptionTesting : PhoneApplicationPage  
{
    // Generate Error to Test Exception Handling
    private void GenerateError()
    {
        Int16 i = Convert.ToInt16("test");
    }
}

处理应用程序级别异常的代码:

// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
StackTrace st = new StackTrace();

var query = st.GetFrames()         // get the frames
        .Select(frame => new
        {                   
            Method = frame.GetMethod(),
            Class = frame.GetMethod().DeclaringType
        });

foreach (var q in query)
{
    if (q.Method.Name.Contains("GenerateError"))
    {
        MessageBox.Show("Class: " + q.Class + ", Method: " + q.Method);
    }
}

if (System.Diagnostics.Debugger.IsAttached)
{
    // An unhandled exception has occurred; break into the debugger
    System.Diagnostics.Debugger.Break();
}
}

解决方法:

不会从发生异常的方法调用Application_UnhandledException方法,因此新的StrackTrace()将没有意义,正如您所发现的那样.

要获取发生异常的位置的堆栈跟踪,请使用e.Exception.StackTrace.
请注意,真正的异常可能包含在另一个异常中,可能是几层深(e.Exception.InnerException).

相关文章

如何在Silverlight4(XAML)中绑定IsEnabled属性?我试过简单的...
我正在编写我的第一个vb.net应用程序(但我也会在这里标记c#,...
ProcessFile()是在UIThread上运行还是在单独的线程上运行.如...
我从同行那里听说,对sharepoint的了解对职业生涯有益.我们不...
我正在尝试保存一个类我的类对象的集合.我收到一个错误说明:...
我需要根据Silverlight中的某些配置值设置给定控件的Style.我...