.Net Error Handling (get calling class/method)

Everyone eventually trys to write an all encompassing error handler that is easy to plug in their methods. Today, I'll provide you with a starting point for creating your own error handling class which will display the classes, method names, and error messages when an error occurs. This is by no means intended to be a complete solution for what to do with errors.

Everyone eventually trys to write an all encompassing error handler that
is
easy to plug in their methods. Today, I'll provide you with a starting point
for creating your own error handling class which will display the classes,
method names, and error messages when an error occurs. This is by no
means
intended to be a complete solution for what to do with errors.
It will
just get started...

In .NET in the System.Diagnostics class, we
can reference the Stack
to retrieve this information. The code below is
a simple console
app demonstrating at a very basic level how it can be
used.

Notice that I've set the main test class: Class1 to inherit
the ErrorTrapper
class.

From there, you can plug in page
redirection code (ASP.NET) or some
other custom notification process.

// your finally clause would go here. Perhaps you need to close
// db connections prior to leaving this page or section of the app.
//
RedirectOnError() will do nothing if the ErrorNumber property of the
//
ErrorTrapper class isn't set to something other than 0

this.RedirectOnError();
System.Console.ReadLine();

}
}
}

ErrorTrapper.cs

using System;
using System.Diagnostics;
using System.Text;

namespace ErrHandler
{

public class ErrorTrapper
{

public int ErrorNumber;
public string ErrorMessage;

public void SetOnError(string sMsg)
{

int
nStackCnt=0;

StringBuilder oString = new StringBuilder();

StackTrace
oStack = new StackTrace(true);

nStackCnt = oStack.FrameCount;

//
I've decided to only show the last few items of the stack.
// They are
displayed in order by most recent frame.

if (nStackCnt > 5)
{ nStackCnt = 5; }

for(int i = 0;i<nStackCnt;i++)
{
//
The first frame (0) is always this method (SetOnError),
// so we don't
want to display it.

Robbe has been a Microsoft MVP in C# since 2004. He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice. Robbe also loves to scuba dive and go deep sea fishing in the Florida Keys or off the coast of Daytona Beach.