星空网 > 软件开发 > ASP.net

扩展Exception,增加判断Exception是否为SQL引用约束异常方法!

在设计数据表时,如果将某些列设置为关联其它表的外键,那么如果对其进行增加、修改操作时,其关联表若没有相匹配的记录则报错,或者在对其关联表进行删除时,也会报错,这就是外键约束的作用,当然除了外键还有许多约束,在此暂不讨论,本篇文章主要讲的是,如何判断是否为SQL的引用约束异常,从而能够更好的将SQL复杂的报错转换为用户能够明白的友好提示。

扩展Exception,增加判断Exception是否为SQL引用约束异常方法(IsSqlReferenceConstraintException):

public static bool IsSqlReferenceConstraintException(this Exception except)    {      var baseEx = except.GetBaseException();      if (baseEx is SqlException)      {        string message = (baseEx as SqlException).Message;        if (message.ToLower().Contains("reference constraint"))        {          return true;        }        else        {          return false;        }      }      else if (baseEx != null && !object.ReferenceEquals(except, baseEx))//如果基类不为空且不等于异常本身,则继续回调查找      {        return IsSqlReferenceConstraintException(baseEx);      }      return false;    }

原生的SQL报错信息如下:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Category_dbo.User_LastEditorID". The conflict occurred in database "mTEM", table "dbo.Category", column 'LastEditorID'.
The statement has been terminated.

而采用扩展方法则会显示出我们预定义的错误信息,调用如下:

public void Remove(int userID)    {      User user=this.repository.Get(t=>t.ID==userID);      if (user != null)      {        try        {          this.repository.Remove(user, true);        }        catch (Exception ex)        {          if (ex.IsSqlReferenceConstraintException()) //判断为引用约束错误,则直接抛出我们自定义的错误          {            throw new Exception("该账号已有与之相关联的其它业务记录,禁止删除!若确认该账号停止使用,可将其设置为禁用即可。");          }        }      }      else      {        throw new Exception("该账号信息不存在或已被删除!");      }    }

 




原标题:扩展Exception,增加判断Exception是否为SQL引用约束异常方法!

关键词:sql

sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流