views:

204

answers:

5

I'm looking at creating a helper method to set an exception's message, automatically setting String.Format, adding in inner exceptions, setting commandline exit codes, etc; something like:

public static void MyExceptionHelper(ExitCode code, string message) {}
public static void MyExceptionHelper(ExitCode code, Exception e) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message, params object[] args) {}
// etc...

The BCL has got a few static classes around that does that sort of thing (eg System.ThrowHelper in mscorlib).
Where is the best place to put these? As overloaded constructors on the exception, in a separate static class (like the BCL), as static methods on the exception itself, or somewhere else?

+1  A: 

I'd just make these constructors for your exception class.

Jon B
A: 

Most of the time, the exception helpers in the BCL are there to support localization (which is usually wrapped up in the SR internal class you'll find in almost all .NET BCL assemblies.) The general idea is that you use a helper method to pass in some basic data for an exception, and the helper handles the retrieval of resources and formatting of data for you to create the exception. The benefit is that you centralize code for exceptions that may be thrown from multiple locations, but which need to be created in the same way. So generally, same idea as any other utility class or inherited object...promotes reuse and maintainability.

As for where to put them...I like to have an "internal area" in each of my assemblies with an exception helper, resource helper, and other internal "assembly support" types.

jrista
+2  A: 

I'd recommend the Exception application block in EnterpriseLibrary, it has a very elegant design for dealing with exceptions and if you don't want all of EntLib I'd recommend copying their interface.

Mark
I agree with you Mark
Johan Leino
A: 

For methods like this, I prefer overloaded constructors. You're clearly using it to create a new object, and that's what a constructor is for.

Once you get into the world of static methods, it's not always clear where they should end up. You'll need to analyze who will use them and how they will be used, then examine the pros and cons of each potential location. Then, you will know where to put them.

John Fisher
A: 

This looks like you have enough custom behavior to want to derive your own exception class, and put this behavior on it. Depending on whether or not you want to interact with the base Exception sine qua Exception later on, you might want to have these be constructors on your derived class that set the base to the passed-in exception, and do your modifications on that exception from within your class; polymorphism will allow that instance to be recast up to a base Exception for interaction from there.

McWafflestix