简体   繁体   中英

Retrieve Query from the Exception thrown

I have a log table where i need to insert the query which causes errors in the code. I have a common function "WritetoLog".

Catch ex As Exception
    writetolog(ex)
End Try

My Question is from the ex how do i take the query which causes error.

eg If the insert command is giving exception i should get like this

SQL Query causes error : Query + ex.Message

SQL Query causes error : Insert into temp("1",'Anitha','TeamLeader',) + Incorrect syntax near ')'

Please help me. Thanks in advance.

Regards Nilofar

Rather than catching an Exception catch the most specific exception type. For SQL Server this would be SqlException . This will allow access to more detailed information (eg Errors property).

If the most derived type doesn't contain the information you need, then you will need to add it yourself. Eg catch the specific type, create you own exception type setting InnerException to the original exception and saving the query before throwing that.

Then catch your exception type where you are handling the error.

To expand upon what Richard is saying, you can create your own exception messages in .NET. You may want to embed the query string inside your exception message and pass the caught exception as the InnerException of your exception. For example:

Sub DoStuffInToTheDatabase()
    Dim sql As String
    Dim dataAccess As New MyDataAccessComponent()
    Dim dt As DataTable

    sql = "Select Top 10 * From Orders"

    Try
        dt = dataAccess.GetDataTable(sql)
    Catch ex As Exception
        Throw New DataException("An exception was thrown with this query: " _
            & sql, ex)   ' <== You put ex into your new DataException'
    End Try
End Sub

Then you might do this in your error logging code:

 Sub WriteErrorLog(ex As Exception)
     Dim errMsg As String
     errMsg = ex.Message
     If Not ex.InnerException Is Nothing Then
         errMsg += " " & ex.InnerException.Message
     End If

     '... '
 End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM