Re-Throwing Exceptions Across Project and Process Boundaries

In reworking a customer’s error handling framework, I wanted to be able to write one error capturing process without having to reference the code across different projects.  I simply wanted to catch the error at the point of failure with a try-catch, perform any error handling locally and then rethrow the error to the calling UI process so that the UI layer could decide what message to display.  So for a database duplicate key I could display, something like "Item already exists".

 I also wanted to capture the error in one project.  I didn’t want the error capturing results spread across different machines when the solution is scaled if the database was unavailable to house the error.  Also, because different applications shared the same middle tiered objects, I didn't want extra logic to determine the what UI was making the call when capturing the error.  I wanted a simple but elegant solution.

 Logically, it seemed to me that this should be done not at the place the error occurred but the UI where you would examine the error to determine what to display to the user.  Therefore I wanted to be able process error handling and rethrow the error at the point of occurrence and then capture the error (capture in the database or in file if database connect is down or server log if file drive is down) and determine what message to display on the front end.  The problem is that I was losing detail if the error was re-thrown over a project boundary.

So I found an article that showed how to keep the detail (http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx) for C# and then changed the code for VB as below:
C#
private static void PreserveStackTrace(Exception exception)
{
  MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
    BindingFlags.Instance | BindingFlags.NonPublic);
  preserveStackTrace.Invoke(exception, null);
}


VB 
Public Shared Sub PreserveStackTrace(ByVal ex As Exception)
        Dim _preserveStackTrace As System.Reflection.MethodInfo = GetType(Exception).GetMethod("InternalPreserveStackTrace", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
        _preserveStackTrace.Invoke(ex, Nothing)
End Sub

So place this code in a common project and right before you re-throw an exception call.

Comments

Popular posts from this blog

Debug VBScript / VBS files in Visual Studio 2010

A good use of Common Table Expressions

Setting Up Visual Studio Environment for Selenium