Rami Alshareef
Rami Alshareef

Reputation: 7150

Inherited Exception class with custom Message property

public class GroupWithSpecificOptionsNotFoundException : Exception
{
    public GroupWithSpecificOptionsNotFoundException(string place, Dictionary<string, string> options)
            : base(string.Format("Group with specific options not found, in ({0}), at ({1})", place, DateTime.Now.ToString()))
    {
        foreach (string key in options.Keys)
        {
            this.Message += string.Format("Option Name : ({0}) with Value : ({1}) not found in this group options set", key, options[key]);
        }

    }
}

The idea is simple, I want to include the key/value objects to the exception's Message. This action can't be performed in the base() thing, nor inside the constructor ("Message is read only").

I found a solution where a static function can do the trick:

public class GroupWithSpecificOptionsNotFoundException : Exception
{
    public static string GenerateOptionValueString(Dictionary<string, string> options)
    {
        string msg = string.Empty;
        foreach (string key in options.Keys)
        {
            msg += string.Format("Option Name : ({0}) with Value : ({1}) not found in this group options set", key, options[key]);
        }
        return msg;
    }

    public GroupWithSpecificOptionsNotFoundException(string place, Dictionary<string, string> options)
            : base (string.Format("Group with specific options not found ({2}), in ({0}), at ({1})",
                    place, DateTime.Now.ToString(), GroupWithSpecificOptionsNotFoundException.GenerateOptionValueString(options)))
    {
    }
}

But I'm not quite satisfied with it! Are there any other workarounds for this and similar cases?

Upvotes: 5

Views: 6473

Answers (1)

MichaelMocko
MichaelMocko

Reputation: 6036

General guidelines of writing exceptions states that you should write Exception with 3 common ctors. For example:

public class MyException : Exception
{
    public MyException()
    {
    }
    public MyException(string message) : base(message)
    {
    }
    public MyException(string message, Exception innerException) 
        : base(message, innerException)
    {
    }
}

I think that you simply need factory which will handle creation of exception with custom message.

Upvotes: 11

Related Questions