Skip to content

Commit

Permalink
Small tweak to error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
colinnuk committed Mar 22, 2024
1 parent 0cee91b commit 111b33e
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions OpenMeteo/OpenMeteoClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public OpenMeteoClient(bool rethrowExceptions, IOpenMeteoLogger? logger = null)
}
catch (HttpRequestException e)
{
_logger?.Error($"Error in {nameof(OpenMeteoClient)}.GetAirQualityAsync(). Message: {e.Message} StackTrace: {e.StackTrace}");
_logger?.Error($"{nameof(OpenMeteoClient)}.GetAirQualityAsync(). Message: {e.Message} StackTrace: {e.StackTrace}");
if (_rethrowExceptions)
throw;
return null;
Expand Down Expand Up @@ -323,12 +323,24 @@ public string WeathercodeToString(int weathercode)
return weatherForecast;
}

var error = await JsonSerializer.DeserializeAsync<ErrorResponse>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
ErrorResponse? error = null;
if((int)response.StatusCode >= 400 && (int)response.StatusCode < 500)
{
try
{
error = await JsonSerializer.DeserializeAsync<ErrorResponse>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
catch (Exception e)
{
_logger?.Error($"{nameof(OpenMeteoClient)}.GetWeatherForecastAsync(). Unable to deserialise error response. This exception will be thrown. Message: {e.Message} StackTrace: {e.StackTrace}");
}
}

throw new OpenMeteoClientException(error?.Reason ?? "Exception in OpenMeteoClient", response.StatusCode);
}
catch (HttpRequestException e)
catch (Exception e)
{
_logger?.Error($"Error in {nameof(OpenMeteoClient)}.GetWeatherForecastAsync(). Message: {e.Message} StackTrace: {e.StackTrace}");
_logger?.Error($"{nameof(OpenMeteoClient)}.GetWeatherForecastAsync(). Message: {e.Message} StackTrace: {e.StackTrace}");
if (_rethrowExceptions)
throw;
return null;
Expand All @@ -352,7 +364,7 @@ public string WeathercodeToString(int weathercode)
}
catch (HttpRequestException e)
{
_logger?.Error($"Error in {nameof(OpenMeteoClient)}.GetGeocodingDataAsync(). Message: {e.Message} StackTrace: {e.StackTrace}");
_logger?.Error($"{nameof(OpenMeteoClient)}.GetGeocodingDataAsync(). Message: {e.Message} StackTrace: {e.StackTrace}");
if (_rethrowExceptions)
throw;
return null;
Expand Down

0 comments on commit 111b33e

Please sign in to comment.