Skip to content

Instantly share code, notes, and snippets.

@mvacha
Created September 18, 2016 21:05
Show Gist options
  • Save mvacha/cebc860bee61c89609b5db9017d68d0a to your computer and use it in GitHub Desktop.
Save mvacha/cebc860bee61c89609b5db9017d68d0a to your computer and use it in GitHub Desktop.
private async Task<Result<T>> Send<T>(string urlSuffix, Func<HttpContent, T> responseParser)
{
try
{
var answer = await SendInternal(urlSuffix);
if (answer.IsSuccessStatusCode)
{
return Result.Ok(responseParser(answer.Content));
}
else
{
return Result.Fail<T>($"HttpRequest failed with code: {answer.StatusCode}");
}
}
catch (AggregateException ex) when (ex.InnerExceptions.Any(e => e is TaskCanceledException))
{
return Result.Fail<T>("HttpRequest was cancelled");
}
}
private async Task<Result> Send(string urlSuffix)
{
try
{
var answer = await SendInternal(urlSuffix);
if (answer.IsSuccessStatusCode)
{
return Result.Ok();
}
else
{
return Result.Fail($"HttpRequest failed with code: {answer.StatusCode}");
}
}
catch (AggregateException ex) when (ex.InnerExceptions.Any(e => e is TaskCanceledException))
{
return Result.Fail("HttpRequest was cancelled");
}
}
private async Task<HttpResponseMessage> SendInternal(string urlSuffix)
{
var cts = new CancellationTokenSource();
_pendingRequests.Add(cts);
var answer = await _client.GetAsync(_uriBase + urlSuffix, cts.Token);
_pendingRequests.Remove(cts);
return answer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment