我正在尝试捕获两次输入电子邮件的异常,并且由于电子邮件是唯一的,因此必须捕获异常。我有以下代码来捕获异常:
自定义异常类:
public class EmailAlreadyExistsException : Exception
{
public EmailAlreadyExistsException(string message) : base(message) { }
}
应该捕获异常的地方:
public void UpdateUser(Customer customer)
{
try
{
this.Entities.SaveChanges();
}
catch (CommonLayer.exceptions.EmailAlreadyExistsException ex)
{
throw ex;
}
}
答案 0 :(得分:0)
晚安,异常引发的不是自定义异常(EmailAlreadyExistsException),因此您的catch(CommonLayer.exceptions.EmailAlreadyExistsException ex)未缓存并继续,请尝试:
public void UpdateUser(Customer customer)
{
try
{
this.Entities.SaveChanges();
}
catch (Exception ex)
{
if(ex.Message.Contains("EmailAlreadyExistsConstraint"))//custom if
throw new CommonLayer.exceptions.EmailAlreadyExistsException(ex.Message);
else
throw ex;
}
}