Capturing all inner exception details c#

I have this extension method which suits my purposes just fine.

public static class ExceptionExtensions {
    public static string ToMessageAndCompleteStacktrace(this Exception exception) {
        Exception e = exception;
        StringBuilder s = new StringBuilder();
        while (e != null) {
            s.AppendLine("Exception type: " + e.GetType().FullName);
            s.AppendLine("Message       : " + e.Message);
            s.AppendLine("Stacktrace:");
            s.AppendLine(e.StackTrace);
            s.AppendLine();
            e = e.InnerException;
        }
        return s.ToString();
    }
}
And use it like this:

using SomeNameSpaceWhereYouStoreExtensionMethods;
try {
    // Some code that throws an exception
}
catch(Exception ex) {
    Console.WriteLine(ex.ToMessageAndCompleteStacktrace());
}

Links : https://stackoverflow.com/questions/18489387/what-is-the-best-practice-for-capturing-all-inner-exception-details

Comments

Popular posts from this blog

How to use DbFunctions.TruncateTime

Provision AWS EC2 Instance and RDS with Terraform, and Deploy Spring Boot App to EC2 Instance via GitHub Action Pipeline

Microsoft Access Connectivity from C#