Xaphann Xaphann - 2 years ago 257
SQL Question

WPF MySQL connection error handling

I am try do some error handling when it comes to connecting to a MySQL database. I want to separate out connection errors and SQL errors. Issue being is the error that is being returned doesn't seem to be a MySQL error but in fact a MS error. This is what I am doing:

using (MySqlConnection con = new MySqlConnection(ConString))
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand(sqlCMD, con);
System.Security.Cryptography.RSACryptoServiceProvider.UseMachineKeyStore = true;
var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
da.SelectCommand = cmd;
catch (Exception x)
//Amazing error catching code

Now lets say I try to connect to a machine that does not have MySQL installed, this is the exception that being returned:

MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()

Now googling "0x80004005 MySQL" returns multiple threads on Stack Overflow about C# connecting to MySQL. Just doing a search for 0x80004005 returns a Windows XP error message page.

So that leaves me with a question what is the best way to determine a connection error vs a SQL error message?

Answer Source

I am not aware of MySQL Exceptions, but you need to use more catch blocks.

just go to definition of each method you used and there you can see what exceptions could be thrown by each method. then instead of using

catch (Exception x)
        //Amazing error catching code

use multiple catch blocks, one after another. see this post for how to group exceptions if there are two many.

Catch multiple exceptions at once?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download