1

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

        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。一些会沿着异常树走并获取最终消息的代码?

4

2 回答 2

0

您可以尝试循环遍历内部异常,直到没有更多异常为止。

就像是

while (error != null)
{
     string doSomething = error.Message;
     error = error.InnerException;
}
于 2013-08-16T05:10:50.103 回答
0

您可以使用

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

更新

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

            throw ex;
        }
于 2013-08-16T05:11:21.387 回答