From a3a5226b833da982de6342b91cfc51d3e0ddf491 Mon Sep 17 00:00:00 2001 From: maxisoft Date: Wed, 22 May 2024 11:37:46 +0200 Subject: [PATCH] Refactor error handling in FreeGamesCommand Moved the exception handling for Reddit JSON loading into the FreeGamesCommand to centralize error management. This change ensures that any exceptions thrown during the retrieval of games from Reddit are caught and logged appropriately, depending on the VerboseLog setting. Simplified the GetPayload method in RedditHelper by removing redundant try-catch blocks. --- ASFFreeGames/Commands/FreeGamesCommand.cs | 18 +++++++++++++++++- ASFFreeGames/Reddit/RedditHelper.cs | 11 +---------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/ASFFreeGames/Commands/FreeGamesCommand.cs b/ASFFreeGames/Commands/FreeGamesCommand.cs index 113f8ad..816efc8 100644 --- a/ASFFreeGames/Commands/FreeGamesCommand.cs +++ b/ASFFreeGames/Commands/FreeGamesCommand.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; +using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; @@ -202,7 +204,21 @@ private async Task CollectGames(IEnumerable bots, ECollectGameRequestS int res = 0; try { - ICollection games = await RedditHelper.GetGames(cancellationToken).ConfigureAwait(false); + ICollection games; + + try { + games = await RedditHelper.GetGames(cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is InvalidOperationException or JsonException or IOException or RedditServerException) { + if (Options.VerboseLog ?? false) { + ArchiSteamFarm.Core.ASF.ArchiLogger.LogGenericException(e); + } + else { + ArchiSteamFarm.Core.ASF.ArchiLogger.LogGenericError($"Unable to load json from reddit {e.GetType().Name}: {e.Message}"); + } + + return 0; + } LogNewGameCount(games, VerboseLog || requestSource is ECollectGameRequestSource.RequestedByUser); diff --git a/ASFFreeGames/Reddit/RedditHelper.cs b/ASFFreeGames/Reddit/RedditHelper.cs index ad5baed..68f324c 100644 --- a/ASFFreeGames/Reddit/RedditHelper.cs +++ b/ASFFreeGames/Reddit/RedditHelper.cs @@ -38,16 +38,7 @@ public static async ValueTask> GetGames(Cancellatio return result; } - JsonNode jsonPayload; - - try { - jsonPayload = await GetPayload(webBrowser, cancellationToken).ConfigureAwait(false); - } - catch (Exception e) when (e is InvalidOperationException or JsonException or IOException or RedditServerException) { - ArchiSteamFarm.Core.ASF.ArchiLogger.LogGenericError($"Unable to load json from reddit {e.GetType().Name}: {e.Message}"); - - return result; - } + JsonNode? jsonPayload = await GetPayload(webBrowser, cancellationToken).ConfigureAwait(false); JsonNode? childrenElement = jsonPayload["data"]?["children"];