我正在使用以下内容来捕获异常类型并添加更多详细信息:
try
{
this.ApplyRules();
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var sb = new StringBuilder();
foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
throw new DbEntityValidationException(
"Entity Validation Failed - errors follow:\n" +
sb.ToString(), ex
); // Add the original exception as the innerException
}
catch (Exception ex)
{
< some code here that would give me more detail about what the exception was >
throw new Exception( );
}
这有效但现在我希望能够捕获其他类型异常的innerException.exceptionMessage。
有没有办法可以为此添加代码,包括所有其他异常类型的最低级别的innerException.exceptionMessage。一些代码会走下异常树并获取最终消息?
答案 0 :(得分:0)
您可以尝试循环遍历内部异常,直到不再有。
像
这样的东西while (error != null)
{
string doSomething = error.Message;
error = error.InnerException;
}
答案 1 :(得分:0)
您可以使用
while (ex.InnerException != null) ex = ex.InnerException;
<强>更新强>:
catch (Exception ex)
{
while (ex.InnerException != null) ex = ex.InnerException;
throw ex;
}