Skip to content

Commit

Permalink
feat: introduce ExceptionInformation to represent a exception JSON se…
Browse files Browse the repository at this point in the history
…rializable
  • Loading branch information
SebastianKuesters committed Jun 12, 2024
1 parent 11aaee2 commit 55c7610
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/Wemogy.Core/Json/ExceptionInformation/ExceptionInformation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;

namespace Wemogy.Core.Json.ExceptionInformation
{
/// <summary>
/// This class represents the most important properties of a exception in a JSON serializable way
/// Thanks to: https://stackoverflow.com/a/72968664
/// </summary>
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);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}
}

0 comments on commit 55c7610

Please sign in to comment.