发布
社区首页 >问答首页 >如果我使用API包装器,我如何在Xamarin上检测和显示HTTP错误消息(404)?

如果我使用API包装器,我如何在Xamarin上检测和显示HTTP错误消息(404)?
EN

Stack Overflow用户
提问于 2019-05-03 16:41:31
回答 1查看 68关注 0票数 0

我目前正在使用Xamarin为手机创建一个多平台应用程序。应用程序的想法基本上是一个口袋妖怪百科全书,它利用了PokeAPi (https://pokeapi.co/),也使用了下面的包装库(https://gitlab.com/PoroCYon/PokeApi.NET)。目前,我希望它的位置,如果用户在搜索栏键入一个错误的精灵宝可梦,它将返回一个警告错误给用户。然而,每次我测试它并输入一个无效的pokemon时,应用程序就会停止,Visual Studio/Xamarin会通知我一个HTTP404错误。我该怎么做呢?

我尝试使用比较语句,如果应用程序接口调用没有找到精灵宝可梦的名字,它应该弹出一个警告,但VS/Xamarin将停止运行应用程序并显示Http404异常。在这一点上我真的不知道该去哪里。

“”“

代码语言:javascript
代码运行次数:0
复制
  async Task PullData()
    {
     LoadingIcon.IsRunning = true;

     string newPokemon = PokemonFind.Text;

     Pokemon p = await DataFetcher.GetNamedApiObject<Pokemon>(newPokemon);


     string PokemonName = p.Name;
     int PokemonHeight = p.Height;
     int PokemonWeight = p.Mass;
     int PokemonXp = p.BaseExperience;
     int PokemonOrder = p.Order;

     OrderLabel.Text = "#" + PokemonOrder;
     NameLabel.Text = "Name: " + PokemonName;
     HeightWeightLabel.Text = "Height/Weight: " + PokemonHeight.ToString() +" dm " + "/" + PokemonWeight.ToString() + " hg";
     ExpLabel.Text = "Experience on defeat: " + PokemonXp.ToString() + "XP";


        LoadingIcon.IsRunning = false;

    }

“”“

我预计它会显示一条警告消息,而不是VS/Xamarin停止程序并抛出HTTP404异常。

EN

回答 1

Stack Overflow用户

发布于 2019-05-03 18:03:32

将您的调用包装在try/catch块中

代码语言:javascript
代码运行次数:0
复制
 try
 {
      async Task PullData()
 }
 catch(HttpRequestException ex)
 {
    //Shows an alert error to the user
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55966189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档