I want to define a custom exception that has two special properties: Field and FieldValue, and I want the message to be built from those two values in the exception constructor. Unfortunately the Message is read only.
This is what I have, but it still requires the message to be passed.
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){}
}
How can I remove the Message as a parameter from the constructor, and then set the message based on the value of Field and FieldValue?
Not sure if I understand your question, but what about this?
public FieldFormatException(Fields field, string value):
base(BuildMessage(field, value))
{
}
private static string BuildMessage(Fields field, string value)
{
// return the message you want
}
I always add a property to my custom exceptions so that I can change the message contents. Actually, I add two properties: one for the message text to be displayed to the user (DisplayMessage), and another for logging many details about the exception (LogMessage) such as user information, the details of a sproc call, data entry details, and so on.
Then, you can leave the Message property alone.
Override it:
public override string Message
{
get
{
return string.Format("My message: {0}, {1}", Field, FieldValue);
}
}
As discussed in the comments, even though you said that you didn't want a message in the constructor, you may want to consider allowing users to optionally pass their own message to the constructor of your exception and having that displayed as well.
Can you not just call the base constructor by constructing your message inline? This would leave message out of it entirely.
public FieldFormatException(string field, string value):
base(field.ToString() + value.ToString())
{
_fieldValue = value;
_field = field;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With