Reputation: 1
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.
e.g. 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
Upvotes: 0
Views: 285
Reputation: 33108
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
Upvotes: 0
Reputation: 109080
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 (e.g. Errors
property).
If the most derived type doesn't contain the information you need, then you will need to add it yourself. E.g. 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.
Upvotes: 1