在設計數據表時,如果將某些列設置為關聯其它表的外鍵,那麼如果對其進行增加、修改操作時,其關聯表若沒有相匹配的記錄則報錯,或者在對其關聯表進行刪除時,也會報錯,這就是外鍵約束的作用,當然除了外鍵還有許多約束,在此暫不討論,本篇文章主要講的是,如何判斷是否為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("該賬號信息不存在或已被刪除!");
}
}