我在这里看到很多人都在谈论从异步功能中捕获异常的方法,但是我没有任何作用。
我使用了一些代码制作了一个IRC机器人:https://github.com/BenFradet/RiotSharp
(因为异常是从WebException
继承的,所以如果你想测试它也应该这样做)
所以我尝试了异步功能。如果来自RiotApi的函数找不到用户,例如GetSummoner()
,则会将{404}抛出为RiotSharpException
。
try
{
RiotSharp.SummonerEndpoint.Summoner summoner = api.GetSummoner(region,name);
SendSummonersDetails(summoner, e.Message.MessageTarget);
}
catch (RiotSharpException ex)
{
string error = string.Format(this.RegionNotFound, command[2]);
irc.Send(new IRCMessage("PRIVMSG", e.Message.MessageTarget, error));
}
我已经使用了那么多时间,我可以抓住那个404。 然而,如果我使用异步版本: 我去了
try
{
RiotSharp.SummonerEndpoint.Summoner summoner = await api.GetSummonerAsync(region,name);
SendSummonersDetails(summoner, e.Message.MessageTarget);
}
catch (RiotSharpException ex)
{
string error = string.Format(this.RegionNotFound, command[2]);
irc.Send(new IRCMessage("PRIVMSG", e.Message.MessageTarget, error));
}
或者对于Task然后离开,try / catch不会捕获异常。
我尝试了我在这里看到的一切: Catch an exception thrown by an async void method
我也尝试了ContinueWith TaskContinuationOptions.OnlyOnFaulted
,但也无效。
我使用VS 2013和framework 4.5ish
我相当失落,并且使用了我在这里找到的所有东西,没有任何效果,也许有人可以想到什么?!
答案 0 :(得分:1)
尝试类似:
try
{
RiotSharp.SummonerEndpoint.Summoner summoner = await api.GetSummonerAsync(region,name);
SendSummonersDetails(summoner, e.Message.MessageTarget);
}
catch (AggregateException ex)
{
foreach(Exception ee in ex.InnerExceptions)
{
RiotException e = ee as RiotException;
string error = string.Format(this.RegionNotFound, command[2]);
irc.Send(new IRCMessage("PRIVMSG", e.Message.MessageTarget, error));
}
}
答案 1 :(得分:0)
好吧它似乎在2015 RC与4.6框架上工作得很好......所以我会坚持这个