Link to home
Start Free TrialLog in
Avatar of conrad2010
conrad2010

asked on

ASP.NET C# Hot to trap a System.Data.SqlClient.SqlException error

On my asp.net C# web page, how can I trap this specific error and redirect to a custom error page?

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server.
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

How are you connecting to your database? If it's through code then it's easy enough by simply wrapping your database code in a try...catch block. If you are using a SqlDataSource component then it might be a little more fiddly.
Avatar of conrad2010
conrad2010

ASKER

try catch sounds good, I'd like to only catch this specific error
ASKER CERTIFIED SOLUTION
Avatar of rawinnlnx9
rawinnlnx9
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
that's it...
Well, that error is reported as a SqlException along with all other Sql errors. If you want to isolate that single error itself then you would have to examine the details of the exception:
SqlConnection conn = new SqlConnection("Your connection string");

try
{
     conn.Open();
}
catch (SqlException ex)
{
                if (ex.Number == 53)
                {
                    // redirect
                }
}
finally
{
     conn.Close();
}

Open in new window