Created
November 10, 2017 21:16
-
-
Save phil-scott-78/c4f046824f0c92cc0a67ec4a763efcc1 to your computer and use it in GitHub Desktop.
Demystify with a lil reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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