neutrofoton

Science, Technology and Life

Extract C# Exception

| Comments

Throwing or catching exception strategy on building an application is a very important to get detail exception message, inner exception and detail strack trace where or which part of line of code that fired the exception.

The following snipped code shows how to extract detail exception message, innner excepion and its detail strack trace to be recorded / written on log.

exception extractor
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
/// <summary>
    /// Extracting <seealso cref="System.Exception"> class include its inner exception
    /// </seealso></summary>
    public sealed class Extractor
    {
        /// <summary>
        /// Parse the specified ex.
        /// </summary>
        /// <param name="exception">Ex.
        public static string Parse(System.Exception exception)
        {
            string errMessage = Environment.NewLine;

            errMessage += FormatErrorDescription(exception);

            while (exception.InnerException != null)
            {
                errMessage += ExtractInnerException(exception.InnerException);
                exception = exception.InnerException;
            }

            errMessage += Environment.NewLine;

            return errMessage;
        }



        /// <summary>
        /// Extract exception message and its strack trace
        /// </summary>
        /// <param name="innerException">inner excepion object
        /// <returns>extracted exception info including message and strack trace</returns>
        static string ExtractInnerException(System.Exception innerException)
        {
            string errMessage = string.Empty;

            errMessage += Environment.NewLine + " InnerException ";
            errMessage += FormatErrorDescription(innerException);

            return errMessage;
        }

        /// <summary>
        /// Formating exception description format
        /// </summary>
        /// <param name="exception">
        /// <returns>Error description</returns>
        static string FormatErrorDescription(System.Exception exception)
        {
            if (exception == null)
                return string.Empty;

            return Environment.NewLine + exception.Message + Environment.NewLine + exception.StackTrace;
        }
    }

Comments