Get the Nitty Gritty Exception Details

CSharp · Console

/Program.cs

using System;
using System.Text;

public class Program
{
	// recursively gather details for the exception
	// and all of its inner exceptions
	public static string ExceptionDetails(System.Text.StringBuilder builder, System.Exception e)
	{
		if (e != null)
		{
			builder.AppendLine("\n\n-----");
			builder.AppendLine("Data:".PadRight(20) + e.Data);
			builder.AppendLine("Message:".PadRight(20) + e.Message);
			builder.AppendLine("StackTrace:".PadRight(17) + e.StackTrace);
			builder.AppendLine("TargetSite:".PadRight(20) + e.TargetSite.ToString());
			builder.AppendLine("-----");
			ExceptionDetails(builder, e.InnerException);
		}

		return builder.ToString();
	}

	public static void Main()
	{
		// mimic an exception
		// that has one inner exception
		try
		{
			try
		    {
				throw new Exception("Some inner exception.");
		    }
		    catch (Exception e)
		    {
			    throw new Exception("Some outer exception.", e);
		    }
		}
		catch (Exception e)
		{
			var builder = new StringBuilder();
			var details = ExceptionDetails(builder, e);
			throw new Exception(details);
		}
	}
}
;