How to catch properly an SqlException: A transport-level error has occurred

Joannes Vermorel picture Joannes Vermorel · Feb 15, 2010 · Viewed 8.2k times · Source

I am getting an SqlException in the logs of .NET 3.5 app, I am looking for the corresponding number (value of the property SqlException.Number).

System.Data.SqlClient.SqlException: A transport-level error has occurred 
when receiving results from the server. (provider: TCP Provider, error: 0 
- The specified network name is no longer available.) at
System.Data.SqlClient.SqlConnection.OnError

I am also getting error such as:

System.Data.SqlClient.SqlException: 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.

Does anyone know how to properly catch those exceptions? (you can also post your answer here)

Answer

AdaTheDev picture AdaTheDev · Feb 15, 2010

That particular error does not come from sys.messages in SQL Server - as it's a problem with the connection. So I don't have the number to hand.

TBH, the best thing you should do is to ensure the Number is written out to the log with the exception - that way, you'll always have the number and message side by side in the logs. May not answer your current question, but it will be the best going forwards IMHO. Not only SqlException.Number but SqlException.ErrorCode too - in instances like this I think .ErrorCode may be the one you actually need (not sure without checking).