我正在使用Entity Framework,当从dbContext.SaveChanges()抛出DbUpdateException时,如何创建自定义异常并抛出它?
我是否会在每个可抛出的SQL约束上创建一个条件:
if (e.InnerException.InnerException.Message.Contains("UNIQUE KEY"))
{
throw new CustomException("message");
}
答案 0 :(得分:2)
throw new DatabaseDataNotFoundException("Cannot find ServerAppConfiguration value for {0}", key);
击败了所有内容。
只需创建自己的异常类,继承自Exception,这是我用于此目的的自定义异常:
public class DatabaseDataNotFoundException : Exception
{
public DatabaseDataNotFoundException() : base() { }
public DatabaseDataNotFoundException(string message) : base(message) { }
public DatabaseDataNotFoundException(string message, params object[] args)
: base(String.Format(CultureInfo.CurrentCulture, message, args)) { }
public DatabaseDataNotFoundException(string message, Exception inner)
: base(message, inner) { }
public DatabaseDataNotFoundException(string message, Exception inner, params object[] args)
: base(String.Format(CultureInfo.CurrentCulture, message, args), inner) { }
protected DatabaseDataNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
然后您的代码变为:
if (e.InnerException.InnerException.Message.Contains("UNIQUE KEY"))
{
throw new DatabaseDataNotFoundException("message");
}