Reputation: 639
We have a custom exception class that works well on our end (see code1 below). Have a scenario that I need to append an error message with this sentence ("The change has not been committed") if the parameter passed in isVerified is true. I did some modification on the class (see code2), but it seems, I still get the original message when error is thrown. I really appreciate your help. Thanks a lot.
code1:
public class BusinessRuleValidationException : Exception
{
public BusinessRuleValidationException(string message):base(message)
{
}
}
code2:
public BusinessRuleValidationException(string message, bool isVerified)
: base(message)
{
if (isVerified)
message += " The change has not been committed.";
}
Upvotes: 1
Views: 70
Reputation: 5609
The issue is that the Exception
base class's constructor is called prior to you modifying the message:
public BusinessRuleValidationException(string message, bool isVerified)
: base(message) // <- problem is here
{
if (isVerified)
message += " The change has not been committed.";
}
So the Message
property has already been set and the modified copy is never actually assigned to anything. As Mark Larter pointed out, you can get around this by simply changing what you pass to the constructor:
public BusinessRuleValidationException(string message, bool isVerified)
: base(string.Format("{0}{1}", message, isVerified ? " The change has not been committed." : string.Empty))
{ }
Upvotes: 2
Reputation: 2363
You might try this, but I haven't tested it:
public BusinessRuleValidationException(string message, bool isVerified)
: base(isVerified ? (message += " The change has not been committed.") : message)
{ }
Upvotes: 0