Tuesday, November 6, 2018

Exception message resolver

How many times you have that situation that you get a user's error message and you're realizing, that you just got the most superficious exception message of a whole exception stack?

Use ResolveExceptionMessageChain from this snippet of code for quick and easy exception message resolving, and then show its return value to the user instead of the message from the last exception object.



using System;
using System.Collections.Generic;
using System.Globalization;

namespace Luegisdorf.Extenders
{
    /// <summary>
    /// Provides extension methods for <c>Exception</c> class
    /// </summary>
    public static class ExceptionExtender
    {
        /// <summary>
        /// Gets all messages from exception and its inner exceptions
        /// </summary>
        /// <param name="ex">
        /// The exception subject to trace
        /// </param>
        /// <param name="delimiter">
        /// Delimiter used between exception messages
        /// </param>
        /// <param name="includeExceptionTypeName">
        /// If <c>true</c>, the name of the type is in the return value included,
        /// otherwise not
        /// </param>
        /// <returns>
        /// A string containing all exception messages
        /// </returns>
        public static string ResolveExceptionMessageChain(this Exception ex,
            string delimiter, bool includeExceptionTypeName)
        {
            List<string> errorList = new List<string>();

            for (var exception = (ex ??
                throw new ArgumentNullException(nameof(ex)));
                    exception != null;
                        exception = exception.InnerException)
            {
                if (includeExceptionTypeName)
                {
                    errorList.Add(string.Format(CultureInfo.CurrentCulture,
                        "{0}: {1}",
                            exception.GetType().Name,
                                exception.Message));
                    // NOTE: the '{0}: {1}' might be replaced to conform culture
                }
                else
                {
                    errorList.Add(exception.Message);
                }
            }

            return String.Join(delimiter, errorList);
            /* NOTE: String.Join will concatenate left to right,
             * for right-to-left cultures you need to modify the code here
             */
        }
    }
}


And that's how you use it:


using System;
using System.Collections.Generic;
using System.Linq;
using Luegisdorf.Extenders;

namespace Luegisdorf.Example
{
    class SampleClass
    {
        public void DoSomething()
        {
            try
            {
                try
                {
                    /*
                     * do something stupid
                     * dont forget, this is only for demonstration ;)
                     */

                    var x = new List<string>();
                    var y = x.First();
                }
                catch (Exception exception)
                {
                    throw new Exception("There was an exception", exception);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception
                    .ResolveExceptionMessageChain(" => ", true));
                /*
                 * The whole chain of exceptions will be put as text
                 * to the console
                 */
            }
        }
    }
}

No comments:

Post a Comment