diff --git a/src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformation.cs b/src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformation.cs new file mode 100644 index 0000000..2fc12e6 --- /dev/null +++ b/src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformation.cs @@ -0,0 +1,37 @@ +using System; + +namespace Wemogy.Core.Json.ExceptionInformation +{ + /// + /// This class represents the most important properties of a exception in a JSON serializable way + /// Thanks to: https://stackoverflow.com/a/72968664 + /// + public class ExceptionInformation + { + public string ExceptionType { get; set; } + public string Message { get; set; } + public string Source { get; set; } + public string? StackTrace { get; set; } + public ExceptionInformation? InnerException { get; set; } + + public ExceptionInformation( + Exception exception, + bool includeInnerException = true, + bool includeStackTrace = false) + { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + + ExceptionType = exception.GetType().FullName ?? exception.GetType().Name; + Message = exception.Message; + Source = exception.Source; + StackTrace = includeStackTrace ? exception.StackTrace : null; + if (includeInnerException && exception.InnerException is not null) + { + InnerException = new ExceptionInformation(exception.InnerException, includeInnerException, includeStackTrace); + } + } + } +} diff --git a/src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformationExtensions.cs b/src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformationExtensions.cs new file mode 100644 index 0000000..f05ad09 --- /dev/null +++ b/src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformationExtensions.cs @@ -0,0 +1,18 @@ +using System; +using Wemogy.Core.Extensions; + +namespace Wemogy.Core.Json.ExceptionInformation +{ + public static class ExceptionInformationExtensions + { + public static ExceptionInformation ToExceptionInformation(this Exception exception, bool includeInnerException = true, bool includeStackTrace = false) + { + return new ExceptionInformation(exception, includeInnerException, includeStackTrace); + } + + public static string ToJson(this Exception exception, bool includeInnerException = true, bool includeStackTrace = false) + { + return exception.ToExceptionInformation(includeInnerException, includeStackTrace).ToJson(); + } + } +}