From 1b174b474c2bf945c03b3de06eb37fa299a1d8cd Mon Sep 17 00:00:00 2001 From: Paul De Smul Date: Fri, 11 Oct 2024 12:36:32 +0200 Subject: [PATCH] Fix crash when uri cannot be reached caused by OpenLibrary being down at the moment --- src/Services/IOService.cs | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/src/Services/IOService.cs b/src/Services/IOService.cs index f620068..2471988 100644 --- a/src/Services/IOService.cs +++ b/src/Services/IOService.cs @@ -34,8 +34,15 @@ public static async Task DownloadFileAsync(string uri) using HttpClient client = new(); if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri? _)) throw new InvalidOperationException("URI is invalid."); - - return await client.GetByteArrayAsync(uri); + try + { + return await client.GetByteArrayAsync(uri); + } + catch (Exception ex) + { + Logger.Error($"Failed to fetch data at {uri}", ex); + return Array.Empty(); + } } public static async Task GetJsonAsync(string uri) { @@ -44,12 +51,18 @@ public static async Task DownloadFileAsync(string uri) JObject? json = null; if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri? _)) throw new InvalidOperationException("URI is invalid."); - - HttpResponseMessage response = await client.GetAsync(uri); - if (response.IsSuccessStatusCode) + try + { + HttpResponseMessage response = await client.GetAsync(uri); + if (response.IsSuccessStatusCode) + { + var data = response.Content.ReadAsStringAsync(); + json = JObject.Parse(data.Result); + } + } + catch (Exception ex) { - var data = response.Content.ReadAsStringAsync(); - json = JObject.Parse(data.Result); + Logger.Error($"Failed to fetch data at {uri}", ex); } return json; }