using Microsoft.Extensions.ObjectPool; using System; using System.Collections.Generic; using System.Text; namespace Opsoft.NetCore.O3App.Shared.Common { public class DefaultErrorFormatter : IErrorFormatter { private readonly ObjectPool _stringBuilderPool; public DefaultErrorFormatter(ObjectPoolProvider objectPoolProvider) { _stringBuilderPool = (objectPoolProvider ?? throw new ArgumentNullException("objectPoolProvider")).CreateStringBuilderPool(); } public string Format(Exception exception) { exception = exception ?? throw new ArgumentNullException("exception"); StringBuilder stringBuilder = _stringBuilderPool.Get(); try { AddError(stringBuilder, exception, 0); return stringBuilder.ToString(); } finally { _stringBuilderPool.Return(stringBuilder); } } internal static void AddError(StringBuilder builder, Exception ex, int indent) { builder.AppendLine($"{new string('\t', indent)} {ex.GetType().FullName}: {ex.Message}"); builder.AppendLine($"{new string('\t', indent)} StackTrace: {ex.StackTrace}"); AggregateException ex2 = ex as AggregateException; if (ex2 != null) { foreach (Exception innerException in ex2.InnerExceptions) { AddError(builder, innerException, indent + 1); } } else if (ex.InnerException != null) { AddError(builder, ex.InnerException, indent + 1); } } } }