为什么Xamarin解决方案中未显示异常的自定义异常消息?

时间:2017-03-12 06:05:24

标签: exception xamarin visual-studio-2017

我一直在理解Xamarin跨平台移动开发的这个例子:

https://msdn.microsoft.com/en-us/library/dn879698.aspx

我通过在代码中复制API密钥两次来犯了错误:

using System;
using System.Threading.Tasks;

namespace XWeatherApp
{
    public class Core
    {
        public static async Task<Weather> GetWeather(string zipCode)
        {
            //Sign up for a free API key at http://openweathermap.org/appid  
            string key = "40aabb59f41e9e88db7be4bab11f49f8";
            string queryString = "http://api.openweathermap.org/data/2.5/weather?zip="
                + zipCode + ",us&appid=" + key + "&units=imperial";

            //Make sure developers running this sample replaced the API key
            if (key == "40aabb59f41e9e88db7be4bab11f49f8")
            {
                throw new ArgumentException("You must obtain an API key from openweathermap.org/appid and save it in the 'key' variable.");
            }

            dynamic results = await DataService.getDataFromService(queryString).ConfigureAwait(true);

            if (results["weather"] != null)
            {
                Weather weather = new Weather();
                weather.Title = (string)results["name"];
                weather.Temperature = (string)results["main"]["temp"] + " F";
                weather.Wind = (string)results["wind"]["speed"] + " mph";
                weather.Humidity = (string)results["main"]["humidity"] + " %";
                weather.Visibility = (string)results["weather"][0]["main"];

                DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
                DateTime sunrise = time.AddSeconds((double)results["sys"]["sunrise"]);
                DateTime sunset = time.AddSeconds((double)results["sys"]["sunset"]);
                weather.Sunrise = sunrise.ToString() + " UTC";
                weather.Sunset = sunset.ToString() + " UTC";
                return weather;
            }
            else
            {
                return null;
            }
        }
    }
}

具体来说,在两条评论之后的行中。

我将应用部署到实体Android手机上。显然我得到了一个例外(在几分钟后寻找失败的代码时,这并不是那么明显)。

该输出窗口中未显示该异常(在Visual Studio 2017中)。我只是在屏幕上看到了这条消息:

Unhandled exception

为什么不提供异常的自定义消息(例如,您必须从openweathermap.org/appid获取API密钥并将其保存在&#39;密钥变量中。)。

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用try / catch?

类似

try{
    await GetWeather(string zipCode);
}
catch(Exception ex) {
    // here you should have your exception
}