Search code examples
asp.netsqlvb.netexceptionsqlexception

Custom error message based on SQL Exception code


What would be the best way to catch the SQL exception code, and then use it to produce a custom error message?

I have a login page which fills out a custom connectionstring, then redirects to a page which uses said connection to access a database. On that page, it can throw errors depending on if I entered the correct login info, or if the database entered is wrong.

Can I just test the connection before I get to that page, or can I catch the exception code and bring it back to the login page?


Solution

  • What I end up doing was just "trying" to open the connection, and if it failed, catch the exception message, and put it on a label on the page.

        Dim queryString As String = "LOGINPROPERTY ( '" + Username + "' , 'property_name' )"
        Dim connection As New SqlConnection(ConnectionString)
        Dim command As New SqlCommand(queryString, connection)
        Try
            connection.Open() 
            Response.Redirect("destination.aspx")
        Catch ex As Exception
            LabelError.Text = ex.Message
        Finally
        End Try