定制代码契约异常消息 [英] Customising Code Contract Exception Messages
问题描述
我有一个代码表示的合同,因为这 - 它验证被存储的实体不为空,有效期为持久性。有用。 。FAB
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);
}
}
不过,我想例外更有用 - 因为任何人都接收该消息会想知道什么实体是无效的,什么是样子。所有实体重写的ToString(),所以我想包括此错误消息:
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());
我已经包含的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?
推荐答案
据文档:
2.10重载合同法
所有的合同方法具有重载一个字符串在
除了布尔条件:
All of the contract methods have overloads that take a string in addition to the boolean condition:
Contract.Requires(X =空,如果x为null,则导弹!是红色的!);
用户提供的字符串将显示只要合同是在运行时违反了
。 目前,它必须是一个编译时常
The user-supplied string will be displayed whenever the contract is violated at runtime. Currently, it must be a compile-time constant.
所以,你问是不可能的
这篇关于定制代码契约异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!