wasSharpNET – Rev 27

Subversion Repositories:
Rev:
///////////////////////////////////////////////////////////////////////////
//  Copyright (C) Wizardry and Steamworks 2016 - License: GNU GPLv3      //
//  Please see: http://www.gnu.org/licenses/gpl.html for legal details,  //
//  rights of fair usage, the disclaimer and warranty conditions.        //
///////////////////////////////////////////////////////////////////////////
// Based on Oguzhan KIRCALI & CDspace @ https://stackoverflow.com/questions/4272579/how-to-print-full-stack-trace-in-exception

using System;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace wasSharpNET.Diagnostics
{
    public static class ExceptionExtensions
    {
        public static string PrettyPrint(this Exception ex, int columns = 80)
        {
            if (ex == null)
                return string.Empty;

            var st = new StackTrace(ex, true);
            var frames = st.GetFrames();
            if (frames == null)
                return string.Empty;

            var sb = new StringBuilder();
            sb.Append(Environment.NewLine);

            foreach (var frame in frames)
            {
                var fileName = frame?.GetFileName();
                if (string.IsNullOrEmpty(fileName))
                    continue;

                sb.Append(Enumerable
                    .Repeat('-', columns)
                    .Concat(Environment.NewLine)
                    .ToArray());
                sb.Append("File: ");
                sb.Append(fileName);
                sb.Append(@" Method: ");
                sb.Append(frame.GetMethod().Name);
                sb.Append(@" Line and Column : ");
                sb.Append(frame.GetFileLineNumber());
                sb.Append(@":");
                sb.Append(frame.GetFileColumnNumber());
                sb.Append(Environment.NewLine);
            }

            sb.Append(Enumerable
                .Repeat('-', columns)
                .Concat(Environment.NewLine)
                .ToArray());
            sb.Append(ex);
            sb.Append(Environment.NewLine);
            sb.Append(Enumerable
                .Repeat('-', columns)
                .Concat(Environment.NewLine)
                .ToArray());

            return sb.ToString();
        }
    }
}

Generated by GNU Enscript 1.6.5.90.