问题
I have a code contract expresses as this - it validates that entity to be stored is not null and is valid for persistence. It works. Fab.
[ContractClassFor(typeof(IRepository<,>))]
internal abstract class ContractsForIRepository<T, TId> : IRepository<T, TId> where T : IEntity
{
private ContractsForIRepository()
{
}
public T Persist(T entity)
{
Contract.Requires<InvalidEntityException>(entity != null, "Entity is null");
Contract.Requires<InvalidEntityException>(entity.IsValidForPersistence(), "Entity not valid for persistence");
return default(T);
}
}
However, I would like the exception to be more useful - as anyone receiving the message will want to know what entity was invalid and what is looked like. All of the entities override ToString(), so I wanted to include this in the error message:
Contract.Requires<InvalidEntityException>(entity.IsValidForPersistence(), "Entity not valid for persistence " + entity.ToString());
I have included ToString to be explicit - it would be called implicitly if I omitted it, but I think it makes my question clearer.
The problem is, this isn't allowed by code contracts and I get the following message.
User message to contract call can only be string literal, or a static field, or static property that is at least internally visible.
Is there any way to include specific data in the exception message?
回答1:
According the documentation:
2.10 Overloads on Contract Methods
All of the contract methods have overloads that take a string in addition to the boolean condition:
Contract.Requires(x != null, "If x is null, then the missiles are red!");
The user-supplied string will be displayed whenever the contract is violated at runtime. Currently, it must be a compile-time constant.
So, what you are asking is not possible.
来源:https://stackoverflow.com/questions/12618265/customising-code-contract-exception-messages