使用 Error.Backtrace().Join("\n")
进行方便的错误跟踪
调试代码时,捕获错误并使用Error的回溯属性
Backtrace 跟踪其来源。
Public Sub Form_Load()
' Your Code Here...
Catch
Message.Error(Error.Text & "\nBacktrace:\n" & Error.Backtrace.Join("\n"))
End
或者...
Public Sub Form_Load()
' Your Code Here...
Catch
Debug Error.Text & "\nBacktrace:\n" & Error.Backtrace.Join("\n")
End
这种方法可以通过仅在调试编译的对话框中显示错误来进一步改进——如本文所示,同时将错误写入发布编译的日志文件。调试编译和发布编译之间的区别可以通过全局静态常数来实现。
Public $bDEBUG As Boolean = False
Public $sPath As String = "~/gambas-log.txt"
Public Sub Form_Load()
' Your Code Here...
Catch
Dim sError As String = Error.Text & "\nBacktrace:\n" & Error.Backtrace.Join("\n")
If $bDEBUG Then
Message.Error(sError)
Else
If LogToFile($sPath, "Error", "My-current-component", sError) = False Then
' Somenting really bad happened!
Endif
Endif
End
Public Function LogToFile(sPath As String, sCategory As String, sTopic As String, sMessage As String) As Boolean
Dim hFile As File
If Exist(sPath) Then
hFile = Open sPath For Write Append
Else
hFile = Open sPath For Write Create
Endif
Print #hFile, Now; " | "; sCategory; " | "; sTopic; " | "; Replace$(Replace$(sMessage, "\n", "; "), ":;", ":")
Close #hFile
Return True
Catch
Return False
End