Skip to content

Instantly share code, notes, and snippets.

@vicentedealencar
Created January 23, 2016 06:55
Show Gist options
  • Save vicentedealencar/1796fd8b461bbf2f5a87 to your computer and use it in GitHub Desktop.
Save vicentedealencar/1796fd8b461bbf2f5a87 to your computer and use it in GitHub Desktop.
var payload = await client.SendAsync(request).ReadAs<PayloadModel>();
using log4net;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace CyberBar.BaseAPI.Util
{
public static class HttpExtensions
{
private static readonly ILog log = LogManager.GetLogger(typeof(HttpException));
public static async Task<T> ReadAs<T>(this Task<HttpResponseMessage> responseTask)
{
var response = await responseTask;
if (!response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var req = await response.RequestMessage.Content.ReadAsStringAsync();
log.Warn(response.RequestMessage.RequestUri);
log.Warn(req);
log.Warn(response.StatusCode);
log.Warn(content);
if (response.StatusCode == HttpStatusCode.Conflict)
{
Console.WriteLine("[http] send error - Conflict");
throw new HttpRequestValidationException("Missing Id on cloud");
}
Exception exception = null;
try
{
exception = content.FromJson<Exception>();
} catch {
exception = new Exception(content);
}
Console.WriteLine("[http] send error - {0}", exception.Message);
throw exception;
}
var contentString = await response.Content.ReadAsStringAsync();
Console.WriteLine("[http] {0} - {1} - {2}", response.RequestMessage.Method, response.RequestMessage.RequestUri.AbsoluteUri, contentString);
return contentString.FromJson<T>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment