你调用的对象是空的

Lef*_*nis 1 .net vb.net visual-studio-2010

我用vb.net开发了一个服务.
此服务是从Windows应用程序安装的,该应用程序在服务启动后立即关闭.
在服务内部我有一个过程"Protected Overrides Sub OnCustomCommand",这个过程正常,直到指针到达我给你的指令:

    Protected Overrides Sub OnCustomCommand(ByVal command As Integer)
                StartLogFile("Custom Command {" & command & "} invoked", EventLogEntryType.Information)
                Dim Position As String
                Dim myFile As String = Nothing
                Dim myTime As String = Nothing
                Try
                    If command = SimpleServiceCustomCommands.StartWorker Then
                        Position = "GetKeyValue Time"
                        myTime = GetKeyValue("Time", "", RegPath)
                        Position = "GetKeyValue Name"
                        myFile = GetKeyValue("Name", "", RegPath)
                        StartLogFile("Notice OnCustomCommand" & vbNewLine & "MyTime= { " & myTime & "}, {MyFile= { " & myFile & "} ", EventLogEntryType.Error)
    .
    .
    .
    Catch ex As Exception
                    StartLogFile("Error OnCustomCommand" & vbNewLine & Position & vbNewLine & ex.StackTrace, EventLogEntryType.Error)
                Finally
                End Try
Run Code Online (Sandbox Code Playgroud)

我根据我读过的通知做了一些更改,现在GetKeyValue没有给我任何错误.但要么没有给我任何价值.

函数Get如下:

Public Function GetKeyValue(ByVal nKey As String, ByVal vKey As String, ByVal sPath As String) As String
        Dim RegKey As RegistryKey
        Dim kValue As String = Nothing
        Dim Pos As String
        If RegKeyExists(sPath) Then
            Try
                RegKey = Registry.CurrentUser.OpenSubKey(sPath, True)
                kValue = CStr(RegKey.GetValue(nKey))
            Catch ex As Exception
                StartLogFile(" GetKeyValue, RegKeyExists(sPath) " & vbNewLine & "{ RegKey= " & RegKey.Name & "}, { kValue= " & kValue & "}, { nKey= " & nKey & "}" & vbNewLine & "Stack Trace= " & ex.StackTrace, EventLogEntryType.Warning)
            End Try
        End If
        Return kValue
    End Function
Run Code Online (Sandbox Code Playgroud)

现在我拥有的是:
没有错误,没有价值
!!!!

Ste*_*ung 5

你的代码显然没有在GetKeyValue()里面的try-catch语句中失败,因为你会从日志中看到错误来自该函数本身.

因此,您的代码必须要么在"False"情况下失败,要么在"True"case的catch块中形成StartLogFile()调用.

假案

请注意,您已经RegKey.Name在日志语句中,并且RegKey很明显null因为您从未设置它(它仅在True情况下设置).我认为这是你的错误所在.

True Case Catch Block

"True"情况下的catch块不会访问任何可能为null的变量的任何属性.但是,StartLogFile本身可能会失败,内部有这样的execption .

交换语句

我有一种感觉,你已经交换了两个StartLogFile()调用(False情况应该在True案例的catch块中,而True案例的catch块中的那个应该是False案例).

避免错误日志记录本身可能会失败

此外,即使在True case块中,也不能假设RegKey为非null,因为Registry.CurrentUser.OpenSubKey可能会失败并且您将无法理解错误的位置,因为您的try-catch块会捕获错误并且它会在错误记录语句中失败!这种类型的bug可能非常令人沮丧,特别是在大型系统中.士气:永远不要让你的错误记录代码太复杂 - 如果它们失败了,它们很难找出发生的事情.

始终在错误日志中包含堆栈跟踪

另外,有没有理由在错误记录中不包含堆栈跟踪?堆栈跟踪将立即指向您的问题代码行.