如何在 vb.net 中使用 Stacktrace 返回错误行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13460656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:26:04  来源:igfitidea点击:

How to use Stacktrace to return Error Line Number in vb.net

vb.neterror-handlingstack-traceerl

提问by user1836775

I am trying to create some sort of error catching method that will return the error line number. We have an abort email that is sent out when a process aborts that gives us the err.numberand err.descriptionbut I would like to know where is actually errors out.

我正在尝试创建某种错误捕获方法,该方法将返回错误行号。我们有一封中止电子邮件,当进程中止时发送给我们err.numbererr.description,但我想知道实际错误在哪里。

I know you can do the following:

我知道您可以执行以下操作:

1: code here
2: code here
3: code here

etc. and use ERL to get the number but it would be tedious to type each line out like that.

等等,并使用 ERL 来获取数字,但像这样输入每一行会很乏味。

Is there either a way to automatically do this or would it be easier to use Stacktrace? If Stacktrace is better could you please show me an example?

有没有办法自动执行此操作,或者使用 Stacktrace 会更容易吗?如果 Stacktrace 更好,你能给我举个例子吗?

采纳答案by Hans Passant

Generating line numbers in exception stack traces is a built-in feature for the CLR. You do however have to provide the information it needs to map a code address to a line number. Switch to the Release configuration of your project. Project + Properties, Compile tab, Advanced Compile Options. Change the "Generate debug info" setting from pdb-only to Full. Deploy the .pdb files along with your program.

在异常堆栈跟踪中生成行号是 CLR 的内置功能。但是,您必须提供将代码地址映射到行号所需的信息。切换到项目的发布配置。项目 + 属性,编译选项卡,高级编译选项。将“生成调试信息”设置从 pdb-only 更改为 Full。将 .pdb 文件与您的程序一起部署。

Beware that the line number you get is always an estimate so do not blindly trust what you see. The mapping is imperfect due to the jitter optimizer inlining methods and otherwise moving code around to make the program run faster.

请注意,您获得的行号始终是一个估计值,因此不要盲目相信您所看到的。由于抖动优化器内联方法和其他移动代码以使程序运行得更快,映射是不完美的。

回答by Mauricio

I have adapted an example from other forum, in my case, I wasn't getting the line number where the error was caused, so I started playing around and found a solution, the code is as follows:

我已经改编了其他论坛的一个例子,在我的例子中,我没有得到导致错误的行号,所以我开始尝试并找到了一个解决方案,代码如下:

Public Class Form1
    Private Sub a2()
        Dim b As Integer = 0
        Dim a As Integer = 1 / b
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
        Try
            a2()
        Catch ex As Exception
            Dim st As New StackTrace(True)
            st = New StackTrace(ex, True)
            MessageBox.Show("Line: " & st.GetFrame(0).GetFileLineNumber().ToString, "Error")
        End Try
    End Sub
End Class

In this example, line 4 will trigger the error exception, but once I applied the principle in a real life application, line was 0, so I started playing with the index in the GetFrame property, it ranges from 0 to 4, when I put 4 in the object, EUREKA, I got the line number causing the problem.

在这个例子中,第 4 行会触发错误异常,但是当我在实际应用中应用这个原理时,第 0 行,所以我开始玩 GetFrame 属性中的索引,它的范围从 0 到 4,当我把4 在对象 EUREKA 中,我得到了导致问题的行号。

回答by julio

    Try
        Dim x As Integer
        x = " "

    Catch ex As Exception
        Dim trace = New Diagnostics.StackTrace(ex, True)
        Dim line As String = Strings.Right(trace.ToString, 5)
        Dim nombreMetodo As String = ""
        Dim Xcont As Integer = 0

        For Each sf As StackFrame In trace.GetFrames
            Xcont = Xcont + 1
            nombreMetodo = nombreMetodo & Xcont & "- " & sf.GetMethod().ReflectedType.ToString & " " & sf.GetMethod().Name & vbCrLf
        Next

        MessageBox.Show("Error en Linea number: " & line & ex.Message & vbCrLf & "Metodos : " & vbCrLf & nombreMetodo)

    End Try

回答by DBithead

If you wish to remain using On Error Goto then simply copy and paste your code into a programmers editor like UltraEdit and insert all the line numbers in a single column editing operation. Make sure you highlight the first column then use Column/Insert Number...

如果您希望继续使用 On Error Goto,那么只需将您的代码复制并粘贴到像 UltraEdit 这样的程序员编辑器中,然后在单列编辑操作中插入所有行号。确保突出显示第一列,然后使用列/插入编号...

Then copy and paste that back into your procedure. Voila except the first case after a select case statement. Remove the line numbers you inserted from the first case entry after every select case.

然后将其复制并粘贴回您的程序中。瞧,除了 select case 语句之后的第一个 case。删除您在每个选择案例后的第一个案例条目中插入的行号。

回答by julio

    Try
        Dim x As Integer
        x = " "

    Catch ex As Exception
        Dim trace = New Diagnostics.StackTrace(ex, True)
        Dim line As String = Strings.Right(trace.ToString, 5)
        Dim nombreMetodo As String = ""

        For Each sf As StackFrame In trace.GetFrames
            nombreMetodo = sf.GetMethod().Name & vbCrLf
        Next

        MessageBox.Show("Error en Linea number: " & line & vbCrLf & ex.Message & vbCrLf & "Metodos : " & nombreMetodo)
    End Try

回答by Meta-Knight

You should definitely use the stack trace, since you can use a global exception catching mechanism that you will need to code only once.

您绝对应该使用堆栈跟踪,因为您可以使用只需要编码一次的全局异常捕获机制。

To get the exact line on which the error was thrown, you will need to ship the pdb files with your application. Those pdb files contain debug information, including the error's line number.

要获得引发错误的确切行,您需要将 pdb 文件与您的应用程序一起发送。这些 pdb 文件包含调试信息,包括错误的行号。

If you want to know how to catch unhandled exceptions gracefully, have a look at this codeproject article.

如果您想知道如何优雅地捕获未处理的异常,请查看这篇 codeproject 文章

回答by tejkumar

You can use the StackTraceto retrieve the line number on an error.

您可以使用StackTrace来检索错误的行号。

Try 
    'Put your code here

Catch ex As Exception
    Dim trace = New Diagnostics.StackTrace(ex, True)
    Dim line As String = Right(trace.ToString, 5)
    MessageBox.Show("'" & ex.Message & "'" & " Error in- Line number: " & line)

End Try