ExceptionHelper
ExceptionHelper provides static methods for working with exceptions
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace NUnit.Framework.Internal
{
public class ExceptionHelper
{
private static readonly Action<Exception> PreserveStackTrace;
static ExceptionHelper()
{
MethodInfo method = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
if ((object)method != null)
try {
PreserveStackTrace = (Action<Exception>)Delegate.CreateDelegate(typeof(Action<Exception>), method);
return;
} catch (InvalidOperationException) {
}
PreserveStackTrace = delegate {
};
}
public static void Rethrow(Exception exception)
{
PreserveStackTrace(exception);
throw exception;
}
public static string BuildMessage(Exception exception)
{
return BuildMessage(exception, false);
}
public static string BuildFriendlyMessage(Exception exception)
{
return BuildMessage(exception, true);
}
public static string BuildStackTrace(Exception exception)
{
StringBuilder stringBuilder = new StringBuilder(GetStackTrace(exception));
foreach (Exception item in FlattenExceptionHierarchy(exception)) {
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append("--");
stringBuilder.Append(item.GetType().Name);
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(GetStackTrace(item));
}
return stringBuilder.ToString();
}
public static string GetStackTrace(Exception exception)
{
try {
return exception.StackTrace;
} catch (Exception) {
return "No stack trace available";
}
}
private static string BuildMessage(Exception exception, bool isFriendlyMessage)
{
StringBuilder stringBuilder = new StringBuilder();
WriteException(stringBuilder, exception, isFriendlyMessage);
foreach (Exception item in FlattenExceptionHierarchy(exception)) {
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" ----> ");
WriteException(stringBuilder, item, isFriendlyMessage);
}
return stringBuilder.ToString();
}
private static void WriteException(StringBuilder sb, Exception inner, bool isFriendlyMessage)
{
if (!isFriendlyMessage)
sb.AppendFormat(CultureInfo.CurrentCulture, "{0} : ", new object[1] {
inner.GetType().ToString()
});
sb.Append(inner.Message);
}
private static List<Exception> FlattenExceptionHierarchy(Exception exception)
{
List<Exception> list = new List<Exception>();
if (exception is ReflectionTypeLoadException) {
ReflectionTypeLoadException ex = exception as ReflectionTypeLoadException;
list.AddRange(ex.LoaderExceptions);
Exception[] loaderExceptions = ex.LoaderExceptions;
foreach (Exception exception2 in loaderExceptions) {
list.AddRange(FlattenExceptionHierarchy(exception2));
}
}
if (exception.InnerException != null) {
list.Add(exception.InnerException);
list.AddRange(FlattenExceptionHierarchy(exception.InnerException));
}
return list;
}
}
}