Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this call to log my exceptions recursive?

I have the following code:

protected string formatException(Exception e)
{
    var exError = "<form>";
        if (e == null)
        {
            throw new ArgumentNullException("e");
        }
        exError += "<fieldset><legend><a href='#'>" +
                  "<span class='show-expanded'>collapse message</span>" +
                  "<span class='show-collapsed'>expand message</span>" +
                  "</a></legend><p>" + e.Message + "</p></fieldset>";
        exError += "<fieldset><legend><a href='#'>" +
                  "<span class='show-expanded'>collapse trace</span>" +
                  "<span class='show-collapsed'>expand trace</span>" +
                  "</a></legend><p>" + e.StackTrace + "</p></fieldset>";

        if (e.InnerException != null)
        {
            // same functionality but for the inner exception and the InnerException.InnerException
        }
    return exError + "</form>";
}

When called it formats the exception message. However I would like to make it include the InnerException and the InnerException.InnerException

Is there some way I could do this recursively or would it be better to put the message format in another function and call that?

like image 585
Samantha J T Star Avatar asked Oct 24 '25 08:10

Samantha J T Star


1 Answers

I know this is an old question and that there is already a marked answer. However, this is how I do it and I'll post this here in case it helps someone:

public static class ExceptionExtension
{
    public static string GetFullTrace(this Exception ex, bool recursive = true)
    {
        string trace = "";

        trace += "Name: " + ex.GetType().Name + "\n";
        trace += "Message: " + ex.Message + "\n";
        trace += "Stack Trace: " + (ex.StackTrace ?? "null") + "\n";

        if (recursive)
        {
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;

                trace += "\n-------------------- Caused by: --------------------\n";
                trace += "Name: " + ex.GetType().Name + "\n";
                trace += "Message: " + ex.Message + "\n";
                trace += "Stack Trace: " + (ex.StackTrace ?? "null") + "\n";
            }
        }
        return trace;
    }
}

A slight change from previous answers is to use an extension method. This way one can simply call it as:

try 
{
    SomeOperationWhichMayThrow();
}
catch(Exception ex) 
{
    LogError(ex.GetFullTrace());
}

I have a project which contains many reusable utilities and extension methods, which I include in most of my projects. ExceptionExtension is one of those utils.

For better performance, consider using a StringBuilder instead.

like image 88
Joel Avatar answered Oct 26 '25 23:10

Joel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!