代码之家  ›  专栏  ›  技术社区  ›  Jim McKeeth

如何让异常在C#中定义自己的消息?

  •  10
  • Jim McKeeth  · 技术社区  · 16 年前

    我想定义一个自定义异常,它有两个特殊属性:Field和FieldValue,我想从异常构造函数中的这两个值生成消息。不幸的是,消息是只读的。

        public class FieldFormatException: FormatException
        {
            private Fields _field;
            private string _fieldValue;
            public Fields Field{ get{ return _field; } }
            public string FieldValue { get { return _value; } }
            public FieldFormatException() : base() { }
            private FieldFormatException(string message) { }
            public FieldFormatException(string message, Fields field, string value): 
                base(message)
            {
                _fieldValue = value;
                _field = field;               
            }
            public FieldFormatException(string message, Exception inner, Fields field, string value): 
                base(message, inner)
            {
                _fieldValue = value;
                _field = field;
            }
            protected FieldFormatException(System.Runtime.Serialization.SerializationInfo info,
                  System.Runtime.Serialization.StreamingContext context): base(info, context){}
        }
    

    如何将消息作为参数从构造函数中删除,然后根据Field和FieldValue的值设置消息?

    6 回复  |  直到 16 年前
        1
  •  25
  •   Stefan Steinegger    16 年前

    我不知道我是否理解你的问题,但是这个呢?

        public FieldFormatException(Fields field, string value): 
            base(BuildMessage(field, value))
        {
        }
    
        private static string BuildMessage(Fields field, string value)
        {
           // return the message you want
        }
    
        2
  •  18
  •   Mark Byers    16 年前

    覆盖它:

        public override string Message
        {
            get
            {
                return string.Format("My message: {0}, {1}", Field, FieldValue);
            }
        }
    

        3
  •  4
  •   womp    16 年前

    您是否可以通过内联构造消息来调用基本构造函数?这将完全忽略这一信息。

     public FieldFormatException(string field, string value): 
             base(field.ToString() + value.ToString())
     {
        _fieldValue = value;
        _field = field;               
     }
    
        4
  •  3
  •   Richard    16 年前

    您可以覆盖消息属性。

    或创建静态辅助对象方法:

    private static string MakeMessage(....) {
      return "Message from parameters of this method";
    }
    

    public FileFormatException(string field, string fieldValue)
      : base(MakeMessage(field, fieldValue) { ... }
    
        5
  •  2
  •   Mark Seemann    16 年前

    你可以覆盖 Exception.Message (这是虚拟的)。

        6
  •  2
  •   DOK    16 年前

    我总是向自定义异常添加属性,以便更改消息内容。实际上,我添加了两个属性:一个用于向用户显示消息文本(DisplayMessage),另一个用于记录有关异常的许多详细信息(LogMessage),例如用户信息、存储过程调用的详细信息、数据输入详细信息等。