Our company consumes a lot of telemetered data from sensors which we consume via an API. So I wrote a method to consume them a bit easier for internal applications. I didn't add a generic to the method, mostly because JSON.NET didn't always build the object correctly. I'd like to remedy that in the future, but as it stands:
public object DownloadFromApi(string url)
{
if (WebRequest.Create(url) is HttpWebRequest request)
{
request.Method = "GET";
request.ContentType = "application/json";
try
{
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
using (Stream stream = response.GetResponseStream())
if (stream != null)
using (var reader = new StreamReader(stream))
{
if (response.StatusCode != HttpStatusCode.OK)
ApplicationProvider.Log.Error(
$"Failed Request with code of {response.StatusCode} at {url}");
return JsonConvert.DeserializeObject(reader.ReadToEnd());
}
ApplicationProvider.Log.Fatal($"No response from {url}");
throw new Exception($"No response from web server {url}");
}
catch (HttpRequestException exception)
{
ApplicationProvider.Log.Fatal($"An unhandled HTTP error has occurred.{Environment.NewLine}{exception.Message}");
throw new Exception(exception.Message);
}
}
ApplicationProvider.Log.Fatal($"Web request failed due to null value. {url}");
throw new Exception($"A null parameter or response has occurred for {url}");
}
I wanted to catch the various issues that may be encountered while consuming, could I improve or do this better?
if/using/using/if/using/ifcascade is pretty scarry! C# is not python. \$\endgroup\$