Home > Mobile >  Catching an exception from a method
Catching an exception from a method

Time:11-11

I'm using a library that throws an exception when an ApiKey doesn't work. Let's say the library has a method called GetAppels(). If the ApiKey isn't valid it returns a message exception, in this case "forbidden".

Notice that GetAppels() is throwing the exception.

Now I would like to know when the ApiKey isn't valid, so I can tell the user that's using a wrong key.

So I did this.

try{
   apiTest api = new apiTest(Key.Text);
   api.GetAppels();
} catch (Exception) { MessageBox.Show("Wrong key!"); }

but this doesn't work, for some reason it continues throwing the other exception before this one. Which it makes sense because the try inside GetAppels is going first than my own try/catch. How could I solve this? How could I catch when the method GetAppels (which isn't the method itself but another one inside this) throws an exception?

EDIT:

GetAppels() method was just an example, this is how the method throws the exception actually.

protected void HandleRequestFailure(HttpResponseMessage response)
{
    try
    {
        if (response.StatusCode == (HttpStatusCode)429)
        {
            var retryAfter = TimeSpan.Zero;
            if (response.Headers.TryGetValues("Retry-After", out var retryAfterHeaderValues))
            {
                if (int.TryParse(retryAfterHeaderValues.FirstOrDefault(), out var seconds))
                {
                    retryAfter = TimeSpan.FromSeconds(seconds);
                }
            }

            string rateLimitType = null;
            if (response.Headers.TryGetValues("X-Rate-Limit-Type", out var rateLimitTypeHeaderValues))
            {
                rateLimitType = rateLimitTypeHeaderValues.FirstOrDefault();
            }
            throw new RiotSharpRateLimitException("429, Rate Limit Exceeded", response.StatusCode, retryAfter, rateLimitType);
        }
        else if (RiotHttpStatusCodeResponse.Contains(response.StatusCode))
        {
            string message;
            try // try get error message from response
            {
                var json = response.Content.ReadAsStringAsync().Result;
                var obj = JObject.Parse(json);
                message = obj["status"]["message"].ToObject<string>();
            }
            catch {
                message = response.StatusCode.ToString();
            }
            throw new RiotSharpException(message, response.StatusCode);
        }
        else
            throw new RiotSharpException("Unexpeced failure", response.StatusCode);
    }
    finally
    {
        response.Dispose(); //Dispose Response On Error
    }
}

This is how I'm catching the exception, maybe I'm doing something wrong.

private bool CheckAPIKEY(string key)
{
    try
    {
        riotApi = RiotApi.GetDevelopmentInstance(key);
        riotApi.Summoner.GetSummonerByNameAsync(
            region: RiotSharp.Misc.Region.Euw, 
            summonerName: summonerName
        );

        return true;
    }
    catch (RiotSharpException) { return false; }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (gameIsRunning)
        MessageBox.Show("Program is already running!");
    else if (summonerName != null) 
    {
        KEY = Key.Text;

        if(!CheckAPIKEY(KEY))
            MessageBox.Show("Your Riot API Key isn't valid.");          
    }
    else
        MessageBox.Show("Couldn't recive information about your SummonerName, is your League of legends game opened?");
}

CodePudding user response:

You're calling an async method and not awaiting the result in any way. You can do either of the following, though the first is preferred by most .NET devs I know.

private async Task<bool> CheckAPIKEY(string key)
{
    try
    {
        riotApi = RiotApi.GetDevelopmentInstance(key);
        await riotApi.Summoner.GetSummonerByNameAsync(
            region: RiotSharp.Misc.Region.Euw, 
            summonerName: summonerName
        );

        return true;
    }
    catch (RiotSharpException) { return false; }
}

or this

private bool CheckAPIKEY(string key)
{
    try
    {
        riotApi = RiotApi.GetDevelopmentInstance(key);
        riotApi.Summoner.GetSummonerByNameAsync(
            region: RiotSharp.Misc.Region.Euw, 
            summonerName: summonerName
        )
        .GetAwaiter()
        .GetResult();


        return true;
    }
    catch (RiotSharpException) { return false; }
}
  • Related