Как отловить исключения в службе WCF? - PullRequest
0 голосов
/ 10 февраля 2019

У меня есть калькулятор, который выполняет основную арифметику с использованием пользовательского ввода от 2 TextBox и вычисляет средние значения (режим, среднее, медиану, диапазон) из числа listBox, которое заполняется с помощью NumericUpDown.

Расчеты выполняются в службе WCf и возвращаются.

Для базовой арифметики try catch достаточно для обработки пустого текстового поля или чего-либо, что не является double.

попытка поймать не работает для средних.Если массив пуст, я получаю "System.InvalidOperationException: Sequence не содержит элементов"

Service.svc.cs

//Define the methods declared in ICalculator.cs by returning with the relevant maths for +, -, *, /, %
    public double Add2Numbers(double num1, double num2)
    {
        return num1 + num2;
    }


//Define the methods declared in ICalculator.cs by returning the mode from an array of decimals
    public decimal Mode(decimal[] ArrayofNumbers)
    {

         /*This is using LINQ to calculate mode.
         * taken from StackOverflow https://stackoverflow.com/questions/19407361/find-most-common-element-in-array/19407938
         * Groups identical values in the array
         * finds group with largest count*/
            decimal mode = ArrayofNumbers.GroupBy(v => v)
            .OrderByDescending(g => g.Count())
            .Select(g => g.Key)
            .First();

        return mode;
    }

Форма

 //When this button is clicked num1 and num2 are added together
    private void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            //parse user input as double num1 and num2
            double num1 = double.Parse(txtNum1.Text);
            double num2 = double.Parse(txtNum2.Text);

            //Make a call to the service Add method, pass in num1 and num2
            txtBoxTotal.Text = ws.Add2Numbers(num1, num2).ToString();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex)
            MessageBox.Show("Enter a numeric value only please, thank you.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtBoxTotal.Text = String.Empty;
        }
    }

   //this button returns most common number in list
    private void BtnMode_Click(object sender, EventArgs e)
    {
        try
        {

            ws.Open();
            //Create new instance of listNumbers
            List<Decimal> listNumbers = new List<Decimal>();



            //for each decimal in listbox...
            foreach (Decimal listItems in listBoxNumbers.Items)
            {
                //Add to listNumbers
                listNumbers.Add(listItems);

            }

            //Convert list to array to find most common item
            decimal[] ArrayofNumbers = listNumbers.ToArray();

            //Print mode to label and console
            Console.WriteLine(ws.Mode(ArrayofNumbers).ToString());
            txtBoxResult.Text = ws.Mode(ArrayofNumbers).ToString();

            ws.Close();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex)
            MessageBox.Show("Enter some values to calculate averages, thank you.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

Кажется, я не могу использовать try catch в служебном коде, так как же работать с обработкой исключений?

TIA!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...