I have an application using .net entity framework I'm attempting to debug. It would make it a lot easier if I could put a try catch in the C# code around entities.SaveChanges() and be able to differentiate errors that are occurring because of sql triggers failing during execution and other errors that occur. I was wondering if anybody knows if this is possible/how to do this.
eg
try{
entities.SaveChanges();
}Catch(Exception e){
if(e is MysterySqlTriggerException){
//do something
}else{
//do something else
}
}
/** Edit **/
Below is the final recursive method I ended up using 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);
}
}
You'll need to search for what you are looking for inside the properties of the raised SqlException
. Inspect the values for the exceptions you are interested in and perform something like the following code:
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
}
catch (MysterySqlTriggerException e)
{
}
catch (SqlException Ex)
{
}
catch (DbUpdateException Ex)
{
}
catch(Exception e)
{
//do something else
}
same as answer from jnovo but I did not see his answer before I wrote it
mocked it up with a 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.