views:

24

answers:

2

Hi all,

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

+1  A: 

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.

Richard
See more properties at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception_properties.aspx
abatishchev
Nilofar
@Nilofar: Need to identify the exception type, and have a look at its properties.
Richard
A: 

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
Ben McCormack
Then i have to pass the sqlquery as a parameter. Then in all the function throughout the module i need to pass the sqlquery also. That will be more work.Thank you very much for ur sincere efforts ... All is well keep smiling .... :-)
Nilofar