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 key / value objects in the exception Message. This action cannot be performed on base()or inside the constructor ("Read-only message").

I found a solution in which 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 very happy with that! Are there any other workarounds for this and similar cases?

+5
source share
1 answer

The general rules for writing exceptions state that you must write an Exception with 3 regular ctors. For instance:

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

, factory, .

+10

All Articles