从动态加载中获取堆栈跟踪信息

时间:2009-10-26 20:26:49

标签: vb.net exception-handling

我的目标是从动态加载的程序集中获取堆栈跟踪信息。如果动态加载的程序集只是将错误返回给调用者,则堆栈跟踪信息不会告诉您位置在发生错误的动态程序集中。如果我抛出自己的异常,传入原始异常,它将被添加为内部异常并且将具有所需的信息。我试图避免更改所有动态程序集以抛出新的异常。有没有人知道从动态加载的程序集中获取堆栈跟踪信息的更好方法?

Public Class ErrorPlugin
    ' Example Function from plug in DLL
    Public Function SimpleExample() As Double


        Dim RentedUnits As Double = 42
        Dim NumberUnits As Double = 0


        Try

            ' Just need to generate exception
            Return RentedUnits \ NumberUnits

        Catch ex As Exception

            ' Give's me no Stack Trace infomation.
            'Throw

            ' This will give me Stack Trace infomation, 
            ' but requires adjusting all the plugins.
            Throw New Exception("Stop dividing by zero.", ex)

        End Try



    End Function
End Class



Imports System.Reflection
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim rpt As Object
        Dim r As Double

        Try

            rpt = LoadReport("C:\ErrorPlugin\bin\Debug\ErrorPlugin.dll")

            r = rpt.SimpleExample()

        Catch ex As Exception

            MsgBox(ex.Message & vbCrLf & ex.StackTrace)

            If ex.InnerException IsNot Nothing Then
                MsgBox(ex.InnerException.StackTrace)
            End If

        End Try


    End Sub


    Public Function LoadReport(ByVal FileName As String) As Object

        Dim m_ReportAssembly As [Assembly]
        Dim m_ReportClass As Type
        Dim rpt As Object

        Try
            m_ReportAssembly = Assembly.LoadFrom(FileName)
            For Each m_ReportClass In m_ReportAssembly.GetTypes
                If m_ReportClass.Name.ToLower = "ErrorPlugin".ToLower Then
                    rpt = Activator.CreateInstance(m_ReportClass)
                    Exit For
                End If
            Next

            Return rpt

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Function

End Class

2 个答案:

答案 0 :(得分:2)

如果你只是投掷,而不是投掷前,你能看到会发生什么吗?从内存中,“throw ex”执行复制,而“throw”实际上重新抛出捕获的异常。我想你的“throw ex”实际上是将堆栈跟踪重置为你的本地代码。

MSDN说如果你要重新抛出异常,你应该通过将它包装在一个新的异常中来增加它的价值,否则你可能不会在你的例子中使用try / catch。

答案 1 :(得分:0)

你有这些外部DLL的调试符号吗?如果您查看堆栈跟踪,并且它显示为“外部代码”,如果您在调试时加载了DLL调试符号,则应将其扩展到DLL堆栈中,因为这些符号将为调试器提供必要的信息以便遍历堆栈

通过手动加载符号,通过“调试”菜单中的“模块”窗口,或者针对DLL的调试版本运行来执行此操作。