【问题标题】:My code is continuously throwing my catch exception and I don't know why我的代码不断抛出我的 catch 异常,我不知道为什么
【发布时间】:2021-10-07 02:25:41
【问题描述】:

我正在创建一个使用 API 访问密钥来获取股票数据信息的项目。用户输入股票代码,然后点击一个按钮,然后加载所有股票信息。但是,当输入正确的股票代码并单击按钮加载信息时,它会不断抛出我设置的 catch 异常,我不知道为什么。我以前从未使用过 try catch,所以我做错了什么吗?

这是我在SettingsTab.cs 中尝试获取股票信息的方法:

async void AddStockButton_Clicked(object sender, EventArgs e)
        {
            string symbol = symbolEntry.Text.ToLower();
            //Create a try catch block to make sure the symbol exists and isn't already added in the list
            try
            {
                //Create new data manager and pass in the users chosen symbol
                DataManager dataManager = new DataManager(symbol);
                StockData newStockData = await dataManager.GetStock();
            if (stockList.Contains(newStockData))
            {
                //If stock does not exists or is a duplicate, display error alert
                //Change success label text to Unsuccessful, change color to red, & make visible
                await DisplayAlert("DUPLICATE STOCK", "This stock is already added to your favorites!", "OKAY");
                successLabel.Text = "Unsuccessful due to duplicate";
                successLabel.TextColor = Color.Red;
                successLabel.IsVisible = true;
            }
            else if (!stockList.Contains(newStockData))
            {
                //If stock exists and not duplicate, add that stock to a list of stockData
                //Display success alert
                //Make success label visible
                stockList.Add(newStockData);
                await DisplayAlert("STOCK ADDED", "This stock has been successfully added to your favorites!", "OKAY");
                successLabel.IsVisible = true;

                MessagingCenter.Send<StockData>(newStockData, "NewStockData");
            }

            }
            catch (WebException ex)
            {
                await DisplayAlert("API FAILED","Unable to retrieve data for that symbol. Please check that you typed it correctly or try again later.", "GO BACK");
                successLabel.Text = "Unsuccessful due to API error";
                successLabel.TextColor = Color.Red;
                successLabel.IsVisible = true;
            }
        }

这是我的 DataManager.cs 类,它获取 API 并将其转换为 json:

public class DataManager
    {
        //This class will be responsible for pulling data from remote API
        //And putting it into the stock data opjects and passing it back to normal UI classes
        //Create variables to use
        WebClient apiConnection = new WebClient();
        //Create a string to start API
        string startAPI = "http://api.marketstack.com/v1/eod/latest?accesskey=<<ACCESS KEY REDACTED>>";
        string Symbols { get; set; }
        
        string ApiEndPoint
        {
            get
            {
                return startAPI + Symbols;
            }
        }

        public DataManager(string symbolsToDownload)
        {
            //make symbols equal to whatever gets passed in
            Symbols = symbolsToDownload;
        }

        public async Task<StockData> GetStock()
        {
            //Create a string representation of the downloaded data from ApiEndPoint
            string apiString = await apiConnection.DownloadStringTaskAsync(ApiEndPoint);

            //Create a JObject to store the apiString as a parsed JObject to get access
            //to the json formatted data
            JObject jsonData = JObject.Parse(apiString);

            //create another JObject
            JObject firstStock = (JObject)jsonData["data"][0];

            Debug.WriteLine(firstStock.ToString());

            //Create a new StockData object
            StockData stockData = new StockData();
            stockData.StockName = firstStock["symbol"].ToString();
            //We need to get the string value and parse it as a Double to define the stock Data property
            stockData.OpenPrice = Double.Parse(firstStock["open"].ToString());
            stockData.ClosePrice = Double.Parse(firstStock["close"].ToString());
            stockData.HighPrice = Double.Parse(firstStock["high"].ToString());
            stockData.LowPrice = Double.Parse(firstStock["low"].ToString());
            stockData.Volume = Double.Parse(firstStock["adj_volume"].ToString());
            stockData.Exchange = firstStock["exchange"].ToString();
            stockData.TradingDay = DateTime.Parse(firstStock["open"].ToString());

            //return the new stock data object
            return stockData;
        }
    }

我只是在使用我的 try catch 错误的方式吗?我在网上找到的所有东西都让我感到困惑。我仍然是一名学生并且正在学习,所以如果这是一个愚蠢的问题,我深表歉意。请帮帮我

【问题讨论】:

  • 当您说“持续”时,您的意思是“持续”吗?连续暗示它在你的代码没有运行的情况下被抛出。持续意味着每次你的代码运行时它都会抛出。
  • 你得到一个例外。但它的讯息是什么?还要检查 InnerException。 “某事”是错误的,异常告诉你 what
  • 什么是ex.ToString()
  • 您不应该在 SO 上发布您的访问密钥。确保你得到一个新的。
  • 有一个例外只是为了告诉您的用户出现问题而不记录收到的信息是非常没用的。传递给处理程序的 Exception 对象充满了有关您在何处以及为什么收到错误的信息。只是现在在异常处理程序中放置一个断点并告诉我们 ex.Message 值是什么

标签: c# json api xamarin.forms


【解决方案1】:

如果您将网址粘贴到浏览器中

string startAPI = "http://api.marketstack.com/v1/eod/latest?accesskey=<<ACCESS KEY REDACTED>>&symbol=AAPL";

你会得到这个非常友好和明确的错误信息

{
  "error":
  {
    "code": "missing_access_key",
    "message": "You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]"
  }
}

accesskey 应该是access_key

【讨论】:

  • 访问密钥已被编辑。这不是问题的一部分。
  • OP 为 access_key 参数使用了错误的名称
【解决方案2】:
  1. 确保access_key的值传输正确且值正确。
  2. 在try的第一行添加断点,看看哪里出错了。
  3. 打印出catch中的“ex”,查看错误的具体信息。

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 2016-11-27
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2014-01-17
    相关资源
    最近更新 更多