如何重写异常,使其返回最低级别的innerException.exceptionMessage



我使用以下内容来捕获异常类型并添加更多详细信息:

        try
        {
            this.ApplyRules();
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            var sb = new StringBuilder();
            foreach (var failure in ex.EntityValidationErrors)
            {
                sb.AppendFormat("{0} failed validationn", 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。一些代码会沿着异常树走下去并获取最终消息吗?

您可以使用

while (ex.InnerException != null) ex = ex.InnerException;

更新

 catch (Exception ex)
        {
            while (ex.InnerException != null) ex = ex.InnerException;
            throw ex;
        }

您可以尝试在内部异常中循环,直到没有其他异常为止。

类似的东西

while (error != null)
{
     string doSomething = error.Message;
     error = error.InnerException;
}