im building an android application and i have some second thoughts on some error handling case.
I have a method that gets data from the internet by calling this method:
public static string StoredDatesList { get => Preferences.Get(nameof(StoredDatesList), string.Empty); set => Preferences.Set(nameof(StoredDatesList), value); } public static async Task<string> GetDraws(Uri url, string date) { Dictionary<string, string> StoredDates = new Dictionary<string, string>(); StoredDates = JsonConvert.DeserializeObject<Dictionary<string, string>>(StoredDatesList); var contents = string.Empty; HttpClient client = new HttpClient(); if (StoredDates != null) if (StoredDates.ContainsKey(date)) { contents = StoredDates[date]; } else { var current = Connectivity.NetworkAccess; if (current != NetworkAccess.Internet) return null; client = new HttpClient(); contents = await client.GetStringAsync(url); var res2 = JsonConvert.DeserializeObject<RootObject>(contents.ToString()); if (180 == res2.content.Count) { StoredDates.Add(date, contents); StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented); } } else { StoredDates = new Dictionary<string, string>(); contents = await client.GetStringAsync(url); var res2 = JsonConvert.DeserializeObject<RootObject>(contents.ToString()); if (180 == res2.content.Count) { StoredDates.Add(date, contents); StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented); } } return contents; }
the if statement current != NetworkAccess.Internet checks if internet is available, when internet is not available i return null and i check if the data is null and im displaying a message(error, internet is not available etc). I find this approach very bad and im trying to think how is the proper way to handle this. i cannot show a message to the user from the GetDraws() function.
Maybe the correct way for this approach is to have a public variable like bool internetError = false; and to make if false every time i call GetDraws(), make it true if internet is not available and check its state after GetDraws? Or should i return as result of GetDraws() the error and check first if the result match of any errors? An issue i have with returning the error message is that i cannot use GetString() function because it is a simple static class with no Android context and in that way i will not have all the application text in the strings.xml. Is maybe a good idea to pass in the GetDraws the context and then do context.GetString()?
Internet connection is not necessary every time GetDraws() is used and that is why im not checking before i called this function for internet connection