具有自定义Message属性的继承Exception类

时间:2011-04-19 08:12:21

标签: c# exception exception-handling

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]);
        }

    }
}

这个想法很简单,我想将键/值对象包含在异常的Message中。此操作无法在base()内容中执行,也无法在构造函数内执行(“Message is read only”)。

我找到了一个静态函数可以解决问题的解决方案:

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)))
    {
    }
}

但我对它不太满意! 对于此类案例和类似案例,还有其他解决方法吗?

1 个答案:

答案 0 :(得分:11)

编写异常的一般准则声明您应该使用3个常见ctors编写Exception。例如:

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

我认为您只需要工厂,它将使用自定义消息处理异常的创建。