Sunday, June 28, 2009

Custom Exception, Converting enum to String

There has to be a better way to do this...

I've got a custom exception with its own types, etc. It started out like this:
public class MyException : Exception
{
public MyException() : base()
{
}

public MyException( String message ) : base( message )
{
}
}

Nothing fancy there, right? At least I can now filter my catches appropriately.

Well, what if I want to use an enum to define the kinds of failures? Like so:

public enum ExceptionType
{
ScrewedUpA,
ScrewedUpB
}

So far, so good.

Until I want to call it thus:

MyException ex = new MyException( MyException.ExceptionType.ScrewedUpA );
throw ex;

Okay, so we add a constructor which takes a MyException.ExceptionType:
public MyException( ExceptionType exType ) 
{}

That's all very nice, but then what? We need some kind of message, right?

Getting the string from the enum isn't that hard. The enum is represented as an int, the type has fields we can query. The field we're interested in will be offset from the enum's int by one (the first field designates the type of the enum).

We'd need to call the constructor with the String signature, which means using the this object. However, the only place this works is in the function signature. Given all of that, this is what I ended up with:
public class MyException : Exception
{
public MyException() : base()
{
}

public MyException( String message ) : base( message )
{
}

public MyException( ExceptionType exType ) :
this (exType.GetType().GetFields()[(int)exType + 1].Name)
{}

public enum ExceptionType
{
ScrewedUpA,
ScrewedUpB
}
}

If there's a better way to do this, I'd like to know. Thanks.

No comments:

Post a Comment