我有一個簡單的服務,通過用戶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