What value does this Exception formatting function add over the built in ToString() method

Viewed 38

I was perusing our large code base I came across this function which is used to format an exception:

    private static string FormatException(Exception ex)
    {
        var errorMessage = new StringBuilder();
        errorMessage.AppendLine($"ErrorMessage : {ex.Message}");
        if (ex.Data.Count > 0)
        {
            var additionalMessage = new StringBuilder();
            foreach (var key in ex.Data.Keys)
            {
                additionalMessage.Append($" {key} : {ex.Data[key]}");
            }
            errorMessage.AppendLine($"AdditionalMessage : 【 {additionalMessage} 】");
        }
        if (!string.IsNullOrWhiteSpace(ex.StackTrace))
        {
            errorMessage.AppendLine($"StackTrace : {ex.StackTrace}");
        }
        if (ex.InnerException != null)
        {
            errorMessage.AppendLine($"InnerException : {ex.InnerException.ToJson(false, true)}");
        }
        return errorMessage.ToString();
    }

At first sight it appears, to me, to offer no real value over the built in ToString() method, given that the information is just going to be run written to a log file.

Am I missing something subtle in the ToString() method that would require something like to ensure the Exception's information is fully collected.

0 Answers
Related