从方法中捕获异常
Catching an exception from a method
我使用的库会在 ApiKey 不起作用时抛出异常。假设库有一个名为 GetAppels() 的方法。如果 ApiKey 无效,它 returns 消息异常,在本例中为“禁止”。
请注意 GetAppels() 正在抛出异常。
现在我想知道 ApiKey 何时无效,这样我就可以告诉用户使用了错误的密钥。
所以我这样做了。
try{
apiTest api = new apiTest(Key.Text);
api.GetAppels();
} catch (Exception) { MessageBox.Show("Wrong key!"); }
但这不起作用,由于某种原因,它继续抛出另一个异常。这是有道理的,因为 GetAppels 内部的尝试比我自己的 try/catch 先进行。我该如何解决这个问题?当 GetAppels 方法(不是方法本身,而是其中的另一个方法)抛出异常时,我该如何捕捉?
编辑:
GetAppels() 方法只是一个示例,这是该方法实际抛出异常的方式。
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
}
}
这就是我捕获异常的方式,也许我做错了什么。
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?");
}
您正在调用一个异步方法并且不以任何方式等待结果。您可以执行以下任一操作,但我认识的大多数 .NET 开发人员更喜欢第一个。
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; }
}
或这个
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; }
}
这样试试
private bool API(string a)
{
try
{
Api = WebApi.GetDevelopmentInstance(a);
Api.Summoner.GetSummonerByNameAsync(
region: WebApi.Misc.Region.Euw,
summonerName: summonerName
)
.GetAwaiter()
.GetResult();
return true;
}
catch (WebApiException) { return false; }
}
我使用的库会在 ApiKey 不起作用时抛出异常。假设库有一个名为 GetAppels() 的方法。如果 ApiKey 无效,它 returns 消息异常,在本例中为“禁止”。
请注意 GetAppels() 正在抛出异常。
现在我想知道 ApiKey 何时无效,这样我就可以告诉用户使用了错误的密钥。
所以我这样做了。
try{
apiTest api = new apiTest(Key.Text);
api.GetAppels();
} catch (Exception) { MessageBox.Show("Wrong key!"); }
但这不起作用,由于某种原因,它继续抛出另一个异常。这是有道理的,因为 GetAppels 内部的尝试比我自己的 try/catch 先进行。我该如何解决这个问题?当 GetAppels 方法(不是方法本身,而是其中的另一个方法)抛出异常时,我该如何捕捉?
编辑:
GetAppels() 方法只是一个示例,这是该方法实际抛出异常的方式。
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
}
}
这就是我捕获异常的方式,也许我做错了什么。
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?");
}
您正在调用一个异步方法并且不以任何方式等待结果。您可以执行以下任一操作,但我认识的大多数 .NET 开发人员更喜欢第一个。
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; }
}
或这个
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; }
}
这样试试
private bool API(string a)
{
try
{
Api = WebApi.GetDevelopmentInstance(a);
Api.Summoner.GetSummonerByNameAsync(
region: WebApi.Misc.Region.Euw,
summonerName: summonerName
)
.GetAwaiter()
.GetResult();
return true;
}
catch (WebApiException) { return false; }
}