扩展Exception,增加判断Exception是否为SQL引用约束异常方法!
2015-04-10 11:16
381 查看
在设计数据表时,如果将某些列设置为关联其它表的外键,那么如果对其进行增加、修改操作时,其关联表若没有相匹配的记录则报错,或者在对其关联表进行删除时,也会报错,这就是外键约束的作用,当然除了外键还有许多约束,在此暂不讨论,本篇文章主要讲的是,如何判断是否为SQL的引用约束异常,从而能够更好的将SQL复杂的报错转换为用户能够明白的友好提示。
扩展Exception,增加判断Exception是否为SQL引用约束异常方法(IsSqlReferenceConstraintException):
原生的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.
而采用扩展方法则会显示出我们预定义的错误信息,调用如下:
扩展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") || message.ToLower().Contains("foreign key")) { 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("该账号信息不存在或已被删除!"); } }
相关文章推荐
- 写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,
- 写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,
- 写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,
- 用Sql添加删除字段,判断字段是否存在的方法
- 用 Sql添加删除字段,判断字段是否存在的方法
- 如何判断一个表是否建立索引约束等信息的SQL语句
- sql 判断 函数 存储过程是否存在的方法
- SQL判断字段列是否存在的方法
- C# B/S程序中出现“异常详细信息: System.Data.SqlClient.SqlException: 用户 'XXX/ASPNET' 登录失败。”的处理方法
- *用Sql添加删除字段,判断字段是否存在的方法
- 求助!!!“测试.Form1”不包含“Form1_Load”的定义,并且找不到可接受类型为“测试.Form1”的第一个参数的扩展方法“Form1_Load”(是否缺少 using 指令或程序集引用?)
- 用Sql添加删除字段,判断字段是否存在的方法
- SQL脚本判断数据库、函数、 存储过程等是否存在的方法
- ASP.login_aspx”不包含“Button1_Click”的定义,并且找不到可接受类型为“ASP.login_aspx”的第一个参数的扩展方法“Button1_Click”(是否缺少 using 指令或程序集引用?)
- sql判断临时表是否存在和创建临时表的方法
- SQL删除字段及判断字段是否存在的方法
- 用Sql添加删除字段,判断字段是否存在的方法
- 异常:Caused by: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'--解决方法
- 编写js扩展方法实现判断一个数组中是否包含某个元素
- 用Sql添加删除字段,判断字段是否存在的方法