aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/ExtensionMethods/ExceptionExtensions.cs
blob: 7b87245b7b79fa919b866e7252750e4c47ef2b78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


/// <summary>
/// Contains <see cref="Exception"/> exception methods.
/// </summary>
public static class ExceptionExtensions
{
    /// <summary>
    /// Flattens the exception by digging on InnerException.
    /// </summary>
    /// <param name="exception">The exception.</param>
    /// <returns></returns>
    public static String FlattenException(this Exception exception)
    {
        var stringBuilder = new StringBuilder();

        while (exception != null)
        {
            stringBuilder.AppendLine(exception.Message);
            stringBuilder.AppendLine(exception.StackTrace);

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }

    /// <summary>
    /// Gets the first exception if this is an aggregated exception.
    /// </summary>
    /// <param name="exception">The exception.</param>
    /// <returns></returns>
    public static Exception GetFirstIfAggregate(this Exception exception)
    {
        var ex = exception as AggregateException;

        if (ex != null && ex.InnerExceptions.Count > 0)
        {
            return ex.InnerExceptions.First();
        }

        return exception;
    }

    /// <summary>
    /// Flattens the exception message in case it is an aggregated exception.
    /// </summary>
    /// <param name="exception">The exception.</param>
    /// <returns></returns>
    public static String FlattenMessage(this Exception exception)
    {
        String message = exception.Message;

        if (exception is AggregateException)
        {
            try
            {
                message = String.Join(Environment.NewLine, (exception as AggregateException).InnerExceptions.Select(x => x.FlattenMessage()));
            }
            catch { }
        }
        else if (exception.InnerException != null)
        {
            message += Environment.NewLine + exception.InnerException.FlattenMessage();
        }

        return message;
    }
}