2

I'm converting the Data Access Code in one of my Asp.Net projects To MSSQL from MySQL. I'm taking this opportunity to attempt to remove any dependencies on provider specific classes or namespaces.

So instead of working directly with MySqlCommand or SqlCommand classes, I'm using DbProviderFactories.GetFactory() methods to return DbCommand objects.

The one issue I'm having is I had code that trapped MySqlExpection exceptions. I'd like a provider agnostic way of trapping Sql exceptions. Is this possible?

Aheho
  • 12,622
  • 13
  • 54
  • 83
  • Just to clarify, the exceptions you are catching are within the Data Layer or outside of it? – Jaime Mendes Sep 01 '13 at 14:55
  • 1
    Sql implements DBexception. I assumed MSSQL does also. Did you try DBexceptoin? I don't have a MSSQL to test with. – paparazzo Sep 01 '13 at 15:24
  • Within the Data Acccess Layer. – Aheho Sep 01 '13 at 15:41
  • @Blam. The Syste.Data.Common.DBException class is exactly what I was looing for. IF you'd like to post that as an answer, I'll upvote it and accept it as the correct answer. – Aheho Sep 01 '13 at 15:48

3 Answers3

0

Without great knowledge to the topic, my thought is that the exceptions are thrown from the concrete classes that provide access to the database. I could guess that some exceptions may be common by nature but other may not. I believe though that it is a good practice to get the specific error logged rather than some abstraction.

Check this SO question and MSDN for more info.

Community
  • 1
  • 1
V-Lamp
  • 1,630
  • 10
  • 18
0

I would recommend something like this. This way, you can either throw an generic sql exception or throw your custom exception associated with a given logic, p.e., ConnectionTimedOutException.

catch(Exception ex)
{
    if(DbProviderFactories.GetException(ex) is CustomSQLException)
    {
        //logic here
    }
    throw;
}
//Factory method
public Exception GetException(Exception ex)
{
    Exception result;
    //Identifying which is the current one
    switch (CurrentProvider)
    {   
        case Provider.SQLServer: 
            //logic here
            result = new CustomSQLServerException(ex); //which extends CustomSQLException
            break;
        default:
            result = ex;
            break;
    }
    return result;
}
Jaime Mendes
  • 643
  • 3
  • 9
0

Sql implements DBexception. I assumed MSSQL does also.
Did you try DBexception?
I don't have a MSSQL to test with.

Aheho
  • 12,622
  • 13
  • 54
  • 83
paparazzo
  • 44,497
  • 23
  • 105
  • 176