在开发项目中我们经常因违反外键约束而删除一条数据而报错误,或者因唯一键而添加数据而报错。
那我们可以在SqlException中的Number属性可以找到错误的类型
如图:
Error Number:标识错误类型的数字;
我们可以创建自定义Exception类(继承自Exception)
在数据访问层捕捉SqlException信息时调用自定义Exception类的来提示信息。
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public static string GetSqlExceptionMessage(int number)
{
//set default value which is the generic exception message
string error = MyConfiguration.Texts.GetString(ExceptionKeys.DalExceptionOccured);
switch (number)
{
case 4060:
// Invalid Database
error = MyConfiguration.Texts.GetString(ExceptionKeys.DalFailedToConnectToTheDB);
break;
case 18456:
// Login Failed
error = MyConfiguration.Texts.GetString(ExceptionKeys.DalFailedToLogin);
break;
case 547:
// ForeignKey Violation
error = MyConfiguration.Texts.GetString(ExceptionKeys.DalFKViolation);
break;
case 2627:
// Unique Index/Constriant Violation
error = MyConfiguration.Texts.GetString(ExceptionKeys.DalUniqueConstraintViolation);
break;
case 2601:
// Unique Index/Constriant Violation
error =MyConfiguration.Texts.GetString(ExceptionKeys.DalUniqueConstraintViolation);
break;
default:
// throw a general DAL Exception
MyConfiguration.Texts.GetString(ExceptionKeys.DalExceptionOccured);
break;
}
return error;
}
下载例子