using System;
using System.Reflection;
namespace StardewModdingAPI.Internal
{
/// Provides extension methods for handling exceptions.
internal static class ExceptionExtensions
{
/*********
** Public methods
*********/
/// Get a string representation of an exception suitable for writing to the error log.
/// The error to summarize.
public static string GetLogSummary(this Exception exception)
{
try
{
switch (exception)
{
case TypeLoadException ex:
return $"Failed loading type '{ex.TypeName}': {exception}";
case ReflectionTypeLoadException ex:
string summary = ex.ToString();
foreach (Exception childEx in ex.LoaderExceptions ?? new Exception[0])
summary += $"\n\n{childEx?.GetLogSummary()}";
return summary;
default:
return exception?.ToString() ?? $"\n{Environment.StackTrace}";
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed handling {exception?.GetType().FullName} (original message: {exception?.Message})", ex);
}
}
/// Get the lowest exception in an exception stack.
/// The exception from which to search.
public static Exception GetInnermostException(this Exception exception)
{
while (exception.InnerException != null)
exception = exception.InnerException;
return exception;
}
}
}