Context
I'm working on a small console application which would allow to input a username of any EUW players on League of Legends and it should try to spectate their games.
The problem
My issue is that I don't really know how I would deal with the JSON file I receive from the Riot API being empty and giving me a 404 error.
The code
Program.cs
var json2 = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + Username);
var summoner = JsonConvert.DeserializeObject<Summoner.RootObject>(json2);
var json = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/" + summoner.id);
var model = JsonConvert.DeserializeObject<Model.RootObject>(json);
long gameid = model.gameId;
string encrypkey = model.observers.encryptionKey;
Spectate(gameid, encrypkey);
Would a simple try-catch suffice? And if so, how would I properly have it attempt the second DeserializeObject based on the success of the first when I can't access the variable summoner outside of the try-catch?
EDIT2: I managed to find a somewhat nice solution that does exactly what I need it to.
bool xd = true;
while (xd == true)
{
Console.Write("Enter username: ");
string Username = Console.ReadLine();
try
{
var json2 = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + Username);
var summoner = JsonConvert.DeserializeObject<Summoner.RootObject>(json2);
var json = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/" + summoner.id);
var model = JsonConvert.DeserializeObject<Model.RootObject>(json);
long gameid = model.gameId;
string encrypkey = model.observers?.encryptionKey;
Spectate(gameid, encrypkey);
xd = false;
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("This summoner does not exist or is not in a game");
Console.WriteLine("Please try again");
continue;
}
}
throw;
}
}