简体   繁体   English

我可以在Entity Framework中尝试/捕获sql server trigger错误

[英]Can I try/catch sql server trigger error in Entity Framework

I have an application using .net entity framework I'm attempting to debug. 我有一个使用.net实体框架的应用程序我正在尝试调试。 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. 如果我可以在entity.SaveChanges()周围的C#代码中放置一个try catch,并且能够区分由于执行期间sql触发器失败而发生的错误以及发生的其他错误,这将使它变得容易得多。 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 . 您需要在引发的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
}

SqlException Class SqlException类

same as answer from jnovo but I did not see his answer before I wrote it 和jnovo的答案一样,但在我写这篇文章之前我没有看到他的回答
mocked it up with a OdbcException 用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM