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();
        }

结果:

Newd

版权声明

作者:扶我起来我还要敲

地址:https://www.cnblogs.com/Newd/p/13099373.html

© Newd 尊重知识产权,引用请注出处

广告位

(虚位以待,如有需要请私信)

原文地址:https://www.cnblogs.com/Newd/p/13099373.html