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:
Login failed for user 'whatever'
14
18456
1
Bad database:
A network something or other
20
-1
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?
Sql Server error codes are documented and you can definitely rely on them!