C#异常信息格式化

private static string ExceptionFormat(Exception ex, string customMessage = "")
        {
            var sb = new StringBuilder();
            sb.AppendLine($"【错误信息】{customMessage}:{ex.Message}");
            sb.AppendLine($"【堆栈跟踪】:{ex.StackTrace}");

            if (ex.InnerException != null)
            {
                sb.AppendLine($"【内部异常】:{ex.InnerException.Message}");
                sb.AppendLine($"【内部异常堆栈跟踪】:{ex.InnerException.StackTrace}");
            }

            if (ex is AggregateException)
            {
                var exs = (ex as AggregateException).InnerExceptions;
                for (int i = 0; i < exs.Count; i++)
                {
                    var item = exs[i];

                    sb.AppendLine($"【第{i + 1}个错误信息】{item.Message}");

                    if (ex.InnerException != null)
                    {
                        sb.AppendLine($"{item.InnerException.Message}");
                        if (item.InnerException.InnerException != null)
                        {
                            sb.AppendLine($"{item.InnerException.InnerException.Message}");
                        }
                    }

                    sb.AppendLine($"【第{i + 1}个错误堆栈跟踪】:{item.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        sb.AppendLine($"{item.InnerException.StackTrace}");
                        if (item.InnerException.InnerException != null)
                        {
                            sb.AppendLine($"{item.InnerException.InnerException.StackTrace}");
                        }
                    }
                }
            }

            return sb.ToString();
        }

结果:

 

posted @ 2020-06-12 14:50  扶我起来我还要敲  阅读(338)  评论(0编辑  收藏  举报