简体   繁体   English

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

[英]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 . 这个想法很简单,我想将键/值对象包含在异常的Message This action can't be performed in the base() thing, nor inside the constructor ("Message is read only"). 此操作不能在base()事物中执行,也不能在构造函数内部执行(“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? 对于此类案例和类似案例,还有其他解决方法吗?

General guidelines of writing exceptions states that you should write Exception with 3 common ctors. 编写异常的一般准则声明您应该使用3个常见ctors编写Exception。 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. 我认为你只需要工厂,它将处理自定义消息的异常创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM