如何在将数据发送到Azure IoTHub时没有互联网连接时捕获异常

时间:2017-04-18 19:32:53

标签: c# azure async-await iot azure-iot-hub

我有一个要求,即我不断向IoT中心发送数据,如果Internet连接断开,我需要将其存储在SQL等本地数据库中。

要将数据发送到IoT中心,我们有asyn方法,即“deviceClient.SendEventAsync” 其中device client是DeviceClient类的对象。

现在因为这是asyn方法,所以当没有互联网连接时它不会抛出任何异常,因此我无法捕获并存储到本地sql db。

内部方法我的代码就像

    try
    {
    await deviceClient.SendEventAsync(message) ;
    }
    catch(AggregateException)
    {
      //If exception found then store same msg to local database.
    }    
    catch(Exception ex)
    {
     //If exception found then store same msg to local database.
    }

但是,如果出现任何故障或没有互联网连接,并且代码执行仍在继续,我永远不会得到任何例外。

请帮我解决这个问题。

如果在调用任何asyn方法时有任何其他方法可以捕获异常,请告诉我。

请找到我用于此操作的整个代码结构。

namespace D2CDeviceDataSender
{
    class Program
    {
        private static DeviceClient deviceClient;
        private static string iotHubUri = string.Empty;
        private static string deviceKey = string.Empty;
        private static string deviceName = string.Empty;

        static void Main(string[] args)
        {
            try
            {
                iotHubUri = ConfigurationManager.AppSettings["IoTHubURI"].ToString();
                deviceName = ConfigurationManager.AppSettings["DeviceName"].ToString();
                deviceKey = ConfigurationManager.AppSettings["DeviceKey"].ToString();
                deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceName, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);

                Task.Factory.StartNew(() => SendDeviceToCloudMessagesAsync1());
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press any key to exit.....");
                Console.ReadLine();
            }
        }

        public static async Task SendDeviceToCloudMessagesAsync1()
        {
            while (true)
            {
                try
                {
                    double avgWindSpeed = 10; // m/s
                    Random rand = new Random();
                    double currentWindSpeed = avgWindSpeed + rand.Next();
                    var telemetryDataPoint = new
                    {
                        DeviceCode = "myFirstDevice",
                        Date = DateTime.UtcNow,
                    };

                    string messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                    var message = new Message(Encoding.ASCII.GetBytes(messageString));
                    Task taskresult = deviceClient.SendEventAsync(message);
                    await taskresult;
                    Console.WriteLine("Data sent to IoT hub :" + DateTime.Now + " " + messageString);
                }
                catch (IotHubCommunicationException ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.InnerException);
                    Console.WriteLine("Internet connectivity down insert data to local database !");
                }
                catch (AggregateException ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.InnerException);
                    Console.WriteLine("Internet connectivity down insert data to local database !");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.InnerException);
                    Console.WriteLine("Internet connectivity down insert data to local database !");
                }

                Thread.Sleep(5000);
            }
        }

    }
}

以下是我的两个观察结果:

  1. 此代码只会在互联网上抛出异常一次 连通性下降。
  2. 从下一次迭代开始,“await taskresult;”停止的方法 响应和从病房迭代,所以我无法捕获任何 异常。
  3. 请回复您的反馈意见。

1 个答案:

答案 0 :(得分:0)

我在循环中有以下代码,不断向IoT Hub发送消息:

try
{
    await deviceClient.SendEventAsync(message);
    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
}
catch (AggregateException e)
{
    Console.WriteLine("{0} > Error Sending message: {1}", DateTime.Now, messageString);
    Console.WriteLine("AggregateException: {0} ", e.Message);
}

如果我将其设置为运行,然后断开计算机与网络的连接,我会在输出中看到:

19/04/2017 09:11:47 > Sending message: {"deviceId":"myFirstDevice","windSpeed":10.042793008518775}
19/04/2017 09:11:52 > Sending message: {"deviceId":"myFirstDevice","windSpeed":8.5088816902175921}
19/04/2017 09:11:58 > Sending message: {"deviceId":"myFirstDevice","windSpeed":10.399840490147398}
19/04/2017 09:12:22 > Error Sending message: {"deviceId":"myFirstDevice","windSpeed":10.388208727533094}
AggregateException: One or more errors occurred.

这表明您可以从 SendEventAsync 方法捕获AggregateExceptions。您在哪个平台上运行代码?