Home > Computers and Internet > Building a close match exception

Building a close match exception

One thing I’ve noticed when trying to do APM programming is that all of the online articles mention how to use the APM, but not how to implement the APM. I actually implemented it with a test tool at work (there is a bunch of overhead) and one of the issues that I came across was exception handling. I don’t mean exception handling in the normal case of catching exceptions, but the best way to generically pass them along. One aspect of .Net which I don’t like is how throwing an exception restarts the stack trace, thereby erasing what it previously might have had. There is the “throw;” syntax, but that doesn’t work for multi threaded code paths. What I wanted was a way to rethrow the original exception type, but with the original exception as an inner exception so that way the original stack trace wasn’t lost. To achieve this I just wrote up this quick method to assist with that.

 

using System;
using System.Reflection;

public class ExceptionReflector
{
    /// <summary>
    /// Builds an exception based off of the given exception so that the stacktrace
    /// of the inner exception is not lost. The returned exception should be close to 
    /// the type of exception passed in.
    /// </summary>
    /// <param name="innerException">The exception to be the inner exception</param>
    /// <returns>Best match exception</returns>
    /// <author>jader3rd</author>
    static Exception BuildException(Exception innerException)
    {
        Exception returnee = null;
        Type targetType = innerException.GetType();
        Type[] desiredTypes = new Type { typeof(String), typeof(Exception) };
        while (null != returnee)
        {
            ConstructorInfo ci = targetType.GetConstructor(BindingFlags.Public, null, desiredTypes, null);
            if (null != ci)
            {
                Object[] parameters = new Object { innerException.Message, innerException };
                returnee = ci.Invoke(parameters);
            }
            else
            {
                targetType = targetType.BaseType;
            }
        }

        return returnee;
    }
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: