2
votes

When the following contract is violated:

Contract.Requires<CustomException>(arg1 != null, "arg1 cannot be null");

the message in CustomException.Message becomes: Precondition failed: arg1 != null arg1 cannot be null. In this situation, how can I prevent code contracts from adding "Precondition failed: arg1 != null" to CustomException.Message?

My assembly is using code contract's "standard contract requires" mode (usage 2 in section 5.1 of code contract's user manual) because I want to use contracts for argument validation on public methods in the release build, thus the reason I'm using Contract.Requires<T> (with the type parameter). In this situation I don't seem to have access to my "arg1 cannot be null" message by itself. I do not wish to try to remove "Precondition failed etc." using string manipulations.

I know that if I instead throw a ContractException (using the non-generic Contract.Requires) I can use reflection to get my message from ContractException.UserMessage. But I don't believe these contracts will work when using "standard contract requires" mode, and anyway I won't be able to globally catch these errors.

1
if u can throw ur own exception, why not throw the same exception but with message as whatever u like? - Kelmen
I'd like to leverage code contracts as much as possible without duplicating the validation logic in if..then statements. Since code contracts provides support for throwing exceptions from public methods, I'm (naively) hoping they provided a way to do what I'm asking. - Keith

1 Answers

2
votes

The Code Contracts User Manual (section 5.1.2 page 21) implies this is the expected behaviour:

RequiresExn(...) is intended to be used with tool support, meaning that they are inherited in all builds and the message strings are generated automatically to include the failing condition

It doesn't mention about being to override the automatically generated messages, so I would assume one cannot. However, as a work-around one could create a custom contract runtime class (see section 7, and in particular section 7.7 of the user manual) that rewrites Requires<Ex> so that it sets Exception.Message as required.