In this method
public static void Detach()
{
try
{
using (var master = new DataContext(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True"))
{
master.ExecuteCommand(string.Format("ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", DatabaseFile));
master.ExecuteCommand(string.Format("exec sp_detach_db '{0}'", DatabaseFile));
}
}
catch (Exception e)
{
... // add to log
}
}
I can receive exception
System.Data.SqlClient.SqlException (0x80131904): The database 'blablabla.mdf' does not exist. Supply a valid database name. To see available databases, use sys.databases.
This happens if Detach()
is called when database is not attached.
My question is: How to swallow only this specific message to avoid logging it?
Text may be localized, so this won't work
if(!(e is SqlException && e.Message.Contains("Supply a valid database name")))
... // log
I am not sure if error code is unique for this specific case (google proves it?)
if(!(e is SqlException && e.Message.Contains("0x80131904")))
... // log
Of course I can do
try { ... } catch {}
But then I have no chance to get into log something unexpected, what may help me to solve problem in case it appears.
You don't want to check the message - you want to check the SQL specific number. You can use the
SqlException.Number
property for this.I would use:
(I would typically not catch plain
Exception
... but that's probably a different matter.)