我有一个简单的服务,通过用户ID返回UserDto:GetUserById。 当用户不存在时,响应DTO将返回一个异常。单一ExceptionDto用于所有错误。DTOs和空结果
因此,当ExceptionDto返回时,客户端并不真正知道服务器端发生了什么。但是,我需要我的客户端将“NotFound”错误与其他所有错误区分开来。另外,我想保持简单的设计。
到目前为止,我正在考虑用FindUsersById替换GetUserById方法。 Find方法将返回一组用户(collection dto)。如果找不到用户,集合将为空。并且返回集合永远不会有多个元素(不允许重复)。
您是否同意或有其他方法来处理?每评论
UPDATE:
- 服务决不会返回null或抛出异常。
- 服务总是返回从基类(DtoBase)
- 每个DTO目的涉及一些实体类型派生DTO对象。每个实体都分配了ID(在我的示例中,我使用长ID为,但Response类可以设为通用)。
DtoBase类:
[DataContract]
public abstract class DtoBase
: IDtoResponseEnvelop
{
[DataMember]
private readonly Response _responseInstance = new Response();
protected DtoBase()
{}
protected DtoBase(long entityId)
{
_responseInstance = new Response(entityId);
}
#region IDtoResponseEnvelop Members
public Response Response
{
get { return _responseInstance; }
}
#endregion
}
每个DTO目的涉及一些实体。如果有一些结果,应该调用具有entityId的构造函数。
Response类是不言自明:
[DataContract]
public class Response
{
#region Constructors
public Response():this(0){}
public Response(long entityId)
{
_entityIdInstance = entityId;
}
#endregion
#region Private Serializable Members
[DataMember]
private BusinessExceptionDto _businessExceptionInstance;
[DataMember]
private readonly IList<BusinessWarning> _businessWarningList = new List<BusinessWarning>();
[DataMember]
private readonly long _entityIdInstance;
#endregion
#region Public Methods
public void AddBusinessException(BusinessException exception)
{
_businessExceptionInstance = new BusinessExceptionDto(exception.ExceptionType, exception.Message, exception.StackTrace);
}
public void AddBusinessWarnings(IEnumerable<BusinessWarning> warnings)
{
warnings.ToList().ForEach(w => _businessWarningList.Add(w));
}
#endregion
#region Public Getters
public bool HasWarning
{
get { return _businessWarningList.Count > 0; }
}
public IEnumerable<BusinessWarning> BusinessWarnings
{
get { return new ReadOnlyCollection<BusinessWarning>(_businessWarningList); }
}
public long EntityId
{
get { return _entityIdInstance; }
}
public bool HasValue
{
get { return EntityId != default(long); }
}
public bool HasException
{
get { return _businessExceptionInstance != null; }
}
public BusinessExceptionDto BusinessException
{
get { return _businessExceptionInstance; }
}
#endregion
}
基本上,Response类聚集体的操作的响应信息,例如:如果有任何值,异常和警告。
“如果没有找到用户,集合将为空,并且返回集合永远不会有多个元素” - 欢迎来到[也许monad!](http://en.wikipedia.org/wiki/Monad_(functional_programming )#The_Maybe_monad) – MattDavey
当你说'service'时,你是指DDD定义中的'service'还是'web service'中的'service'? –
在DDD中。使用DTO的服务 – Tenek