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?
According the documentation:
So, what you are asking is not possible.