Naveen Tiwari
Naveen Tiwari

Reputation: 13

How to handle sql exception in C#?

I am using catch block with SqlException, but I want to show custom messages rather than exception itself. So how do I filter out the messages. Like say I want to catch a Unique Key Constraint Violation. Is there some error code which i can use to determine the error.

 protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {

                objuser.username = txt_email.Text;
                objuser.email = txt_username.Text;
                objuser.password = txt_password.Text;
                int i = BusinessUser.BusinessRegisterUser(objuser);
                if (i > 0)
                {
                    Session["user_authenticate"] = "Verified";
                    Session["user_email"] = objuser.email; //  sql exception handle for uniqe key
                    Response.Redirect("user_registration.aspx");
                }
            }
            catch (SqlException ex)
            { 
              // Handle Exception here if e-mail already exists
            }
            catch (Exception ex)
            {

            }

        }

Upvotes: 1

Views: 93

Answers (1)

nvoigt
nvoigt

Reputation: 77294

You can check the Number property of your SqlException. A full list of possible errors can be found here.

Upvotes: 2

Related Questions