Search code examples
c#enterprise-librarysqlconnection

Get SqlConnection failure reason


I have a method that returns whether a connection can be opened.

However, in case of failure I need to notify users whether they've provided bad login credentials or if there's a problem with the database.

Current code:

try 
{
    Database db = new SqlDatabase(connectionString);
    using(var connection = db.CreateConnection())
    {
        connection.Open();
        return true;
    }
}
catch (Exception ex)
{
    return false;
}

Whether it's a problem with credentials or database, the exception is always SqlException.

However, I've noticed the following differences:

Bad credentials:

  • Message: Login failed for user 'whatever'
  • Class: 14
  • Number: 18456
  • State: 1

Bad database:

  • Message: A network something or other
  • Class: 20
  • Number: -1
  • State: 0

...So yes, there are differences, but I'm not sure I can rely on these numbers (and checking the string value of the message makes me feel like I need to take a shower).

According to MSDN, the Number property can be a Win32 error code or a server error code, Class denotes severity and State can give different error codes different meanings.

Is there a better way to determine connection failure?


Solution

  • Sql Server error codes are documented and you can definitely rely on them!