How to timeout "A network-related or instance-specific error occurred while establishing a connection to SQL Server" error

StackOverflow https://stackoverflow.com/questions/17550900

Question

I am using sql server and sometimes my database goes down for maintenance. I have error handling code so the user don't see error page, instead they see a nice and friendly error message. My question is: When the database is down, It takes an awfully long time for the page to load and show the error message. I thought it had something to do with the timeout property, but changing it using

command.CommandTimeout = 5;

or

Connect Timeout=5; in web.config in connectionString doesn't seem to help and it still take a long time for the page to load (about 40 sec). Is there a way to minimize this time?

The exception that gets thrown and logged is

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

No correct solution

OTHER TIPS

Ok then.

I would create a base class for all your "data access layer" classes.

public class DataBaseLayer ()
{

public DataBaseLayer()
{ /* check for appSetting here and throw a SqlServerMaintenanceModeException exception (custom exception) */}

}


public class EmployeeDataLayer :  DataBaseLayer ()
    {
public EmployeeDataLayer() : base ()
}

In the constructor, I would check an appSetting...for "true" or "false".........and throw a CustomException

public class SqlServerMaintenanceModeException : ApplicationException

{}

throw it in the constructor of the DataBaseLayer......then have everything else handle it.

That way...only "db driven" pages are affected.

The small reason I don't like checking for a "timeout" is that..

  1. It is a tad unpredictable.
  2. Sometimes that is a normal exception.............like a switch on your network goes by. How will you tell the difference?

I dislike ambiguous exceptions tremendously.

If your server connect timeout takes too long, check:

  • type of your connection string (.NET provider, OLEDB or other), they might have different names for same thing
  • if you really are using the connection string in question; you might be actually using completely different connection string
  • isolate your try/catch timeout block to wrap just conn.Open() - that way you really know that opening a connection takes too long; I'm not saying your exception is not indicative, just that I'm not 100% sure that all that time is spent only for conn.Open()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top