public class TaskHTTP_ClientClient
{
private readonly HttpClient httpClient = new HttpClient();
private readonly JsonSerializerOptions serializerOptions = new() { PropertyNamingPolicy = null };
public override async System.Threading.Tasks.Task RetrieveSelection(
TaskGateway.SelectionRetrieving.RequestParameters requestParameters
)
{
HttpResponseMessage response = await this.httpClient.GetAsync(/* */);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync();
}
throw new Exception("Failed to retrieve tasks selection.", response.StatusCode);
}
}
Однако таким образом мы не узнаем точную причину исключения, поскольку она находится внутри данных ответа.
public class TaskHTTP_ClientClient
{
private readonly HttpClient httpClient = new HttpClient();
private readonly JsonSerializerOptions serializerOptions = new() { PropertyNamingPolicy = null };
public override async System.Threading.Tasks.Task RetrieveSelection(
TaskGateway.SelectionRetrieving.RequestParameters requestParameters
)
{
HttpResponseMessage response = await this.httpClient.GetAsync(/* */);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync();
}
string errorData = await response.Content.ReadAsStringAsync();
throw new Exception(errorData);
}
}
Лучше, но если перехватить это исключение и System.Diagnostics.Debug.WriteLine(), его будет трудно прочитать:

System.Exception: {"type":"https://tools.ietf.org/html/rfc9110#sec ... "Произошла одна или несколько ошибок проверки.","status":400,"errors":{"optionalFiltering":["Необязательное поле Filtering требуется."]},"traceId":"00-7612a7eb6ea01309ea7dd827171dea35-1486e2e916e49364-00"
at Client.Data.FromServer.TaskHTTP_ClientGateway.RetrieveSelection(RequestParameters requestParameters)
в Client.SharedState.TasksSharedState.retrieveTasksSelection(Options options)
Почему бы не украсить данные об ошибках?
public class TaskHTTP_ClientClient
{
private readonly HttpClient httpClient = new HttpClient();
private readonly JsonSerializerOptions serializerOptions = new() { PropertyNamingPolicy = null };
public override async System.Threading.Tasks.Task RetrieveSelection(
TaskGateway.SelectionRetrieving.RequestParameters requestParameters
)
{
HttpResponseMessage response = await this.httpClient.GetAsync(/* */);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync();
}
object errorData = await response.Content.ReadFromJsonAsync();
throw new Exception(
System.Text.Json.JsonSerializer.Serialize(
errorData,
options: new System.Text.Json.JsonSerializerOptions
{
WriteIndented = true
}
)
);
}
}

Теперь мы можем мгновенно узнать причину ошибки.
Я делаю что-то не так?
Обновить
Я использовал исключение непосредственно в приведенном выше примере, чтобы сохранить его просто, но в моем реальном приложении я создал наследника класса Exception.
public class DataFetchingFailedException : Exception
{
public DataFetchingFailedException(string message) : base(message) {}
public DataFetchingFailedException(string message, object errorData) :
base(DataFetchingFailedException.BuildMessage(message, errorData)) {}
private static string BuildMessage(string message, object errorData)
{
return message + "\n" +
System.Text.Json.JsonSerializer.Serialize(
errorData,
options: new System.Text.Json.JsonSerializerOptions
{
WriteIndented = true
}
);
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... nation-whe
Мобильная версия