Skip to content

Instantly share code, notes, and snippets.

@phil-scott-78
Created November 10, 2017 21:16
Show Gist options
  • Save phil-scott-78/c4f046824f0c92cc0a67ec4a763efcc1 to your computer and use it in GitHub Desktop.
Save phil-scott-78/c4f046824f0c92cc0a67ec4a763efcc1 to your computer and use it in GitHub Desktop.
Demystify with a lil reflection
using System;
using System.Reflection;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
BlowUp();
}
catch (Exception e)
{
Console.WriteLine(Demystify(e).ToString());
}
}
static void BlowUp()
{
throw new Exception("kablam!");
}
static T Demystify<T>(T exception) where T : Exception
{
var memberwiseClone = exception.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
var stackTraceString = exception.GetType().GetField("_stackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
var newException = (T)memberwiseClone.Invoke(exception, null);
stackTraceString.SetValue(newException,$"New StackTrace{Environment.NewLine}{exception.StackTrace}" );
return newException;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment