Can I try / catch an error starting SQL server in Entity Framework

I have an application using .net entity framework I am trying to debug. It would be much simpler if I could put a catch attempt in C # code around .SaveChanges () objects and be able to distinguish between errors that occur due to malfunctioning sql scripts and other errors. I was wondering if anyone knows if this is possible / how to do it.

eg,

try{
    entities.SaveChanges();
}Catch(Exception e){
     if(e is MysterySqlTriggerException){
         //do something
     }else{
         //do something else
     }
}

/ ** Edit ** /

Below is the final recursive method that I used to handle this

    public void HandleTriggerException(Exception e)
    {
        if (e is SqlException)
        {
            //check if it is from a trigger
            SqlException sqlException = (SqlException)e;
            if (sqlException.Procedure.Contains("tr_")) //all my trigger names start with "tr_"
            {
                //trigger failed.  Handle exception.
            }
        }

        if (e.InnerException != null)
        {
            HandleTriggerException(e.InnerException);
        }
    }
+3
source share
2 answers

, SqlException. - :

void HandleSqlException(SqlException e)
{
     if (sqlex.Procedure == "myTrigger" || sqlex.Message.Contains("myTrigger"))
     {
        // act
     }        
}

...

try
{
    entities.SaveChanges();
} 
catch (System.Data.DataException dex)
{
    if (dex.InnerException is SqlException)
       HandleSqlException((SqlException)dex);
}
catch (SqlException sqlex)
{
    HandleSqlException(sqlex);
} 
catch (Exception e) 
{
    // non-SQL exception handling
}
+2
catch (MysterySqlTriggerException e)
{
}
catch (SqlException Ex)
{
} 
catch (DbUpdateException Ex)
{
}   
catch(Exception e)
{
     //do something else
}

SqlException

, jnovo, , . OdbcException

public void SQL()
{
    try
    {

    }
    catch (SqlException Ex)
    {
        SqlHandler(Ex);
    }
    catch (OdbcException Ex)
    {
        if (Ex.InnerException is SqlException) SqlHandler((SqlException)Ex.InnerException);
    }
    catch (Exception Ex)
    {
    }


}
void SqlHandler(SqlException Ex)
{
    // handle
}
+1

All Articles