[英]Getting errors from a method that already has a return type
我有一種嘗試創建多個用戶帳戶的方法。 如果成功,則返回用戶ID列表,否則我需要獲取錯誤列表。 實現此目標的最佳方法是什么?
這是我已實現的精簡版本:
public class RXGAdapter {
private List<string> _errors;
public IEnumerable<int> CreateAccounts(string username, int quantity)
{
ResetErrors();
var accountIDs = new List<int>();
for (int i = 1; i <= quantity; i++)
{
int accountID = CreateAccount(username + i);
if (_errors.Count > 0)
{
return new List<int>();
}
accountIDs.Add(accountID);
}
return accountIDs;
}
public int CreateAccount(string username)
{
try {
// Make HTTP request to the server
// Parse the ID from of the response if successful
return id;
}
catch (WebException e)
{
// Parse the errors from the response if unsuccessful
_errors.AddRange(errors);
return -1;
}
}
public void ResetErrors()
{
_errors = new List<string>();
}
public bool HasErrors()
{
return _errors.Count > 0;
}
public IEnumerable<string> Errors
{
get { return _errors; }
}
}
我擔心這會破壞SRP。
您可以引發自定義異常,其中包含錯誤列表作為自定義異常的屬性。
另一種方法是,如果允許您更改CreateAccounts函數簽名,則可以將列表中每個帳戶創建的狀態作為CreateAccounts函數的out參數返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.