【发布时间】:2018-05-29 12:16:13
【问题描述】:
我目前正在尝试为我的 IoT 学校项目开发简单的 Web 应用程序。至于现在它应该只从我的 Raspberry 调用直接方法。 我正在使用 Azure SDK for C#。
这是代码的样子:
控制器:
public ActionResult changeState(int? id, bool enable)
{
string conn_str = (from u in db.Users join h in db.Hubs on
u.Hub.HubId equals h.HubId
where u.UserName == User.Identity.Name select h.connection_str).First();
Cloud2Device c2d = new Cloud2Device(conn_str);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Rp rp = db.Rps.SingleOrDefault(r => r.RpId == id);
if (rp == null)
{
return HttpNotFound();
}
//IoT stuff
try
{
c2d.EnableRaspberry("myDeviceId").Wait();
}
catch(Exception ex)
{
//do something
}
rp.is_enabled = enable;
db.SaveChanges();
return RedirectToAction("Index");
}
物联网实用程序:
public class Cloud2Device
{
private ServiceClient s_serviceClient;
public Cloud2Device(string conn_str)
{
s_serviceClient = ServiceClient.CreateFromConnectionString(conn_str);
}
public async Task EnableRaspberry(string deviceId)
{
var methodInvocation = new CloudToDeviceMethod("EnableRaspberry") { ResponseTimeout = TimeSpan.FromSeconds(2) };
var response = await s_serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);
Debug.WriteLine(response.GetPayloadAsJson());
}
}
问题是从调试输出中我可以看到异常 Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException 被抛出,但它没有被 try-catch 块处理。
Application Insights Telemetry (unconfigured): "name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2018-05-29T12:04:59.4748528Z","tags":{"ai.internal.sdkVersion":"rddf:2.2.0-738","ai.internal.nodeName":"5CG6455YJ4.ericsson.se","ai.cloud.roleInstance":"5CG6455YJ4.ericsson.se"},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"/twins/myDeviceId/methods","id":"8/ZMgqG4iNc=","data":"https://utiliothub.azure-devices.net/twins/myDeviceId/methods?api-version=2017-10-15","duration":"00:00:01.2380000","resultCode":"404","success":false,"type":"Http","target":"utiliothub.azure-devices.net","properties":{"DeveloperMode":"true"}}}}
Exception thrown:'Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException' in Microsoft.Azure.Devices.dll
Exception thrown:'Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException' in mscorlib.dll
The thread 0x3834 has exited with code 0 (0x0).
谁能告诉我如何在我的应用程序中捕获和处理这个异常?提前感谢您的回答。
【问题讨论】:
-
现在可以了吗?
-
我不熟悉那些库,但似乎异常发生在你之外
try/catch块。例如:你的ServiceClient.CreateFromConnectionString(conn_str);是什么? -
不要使用
c2d.EnableRaspberry("myDeviceId").Wait();。使动作异步,即将签名更改为public async Task<ActionResult> changeState并使用await c2d.EnableRaspberry("myDeviceId");。现在代码阻塞一个线程并在另一个线程上运行调用 -
BTW
.Wait()总是抛出一个AggregateException来包装实际的异常。如果您在异常消息中没有看到它,则表示该错误是由其他东西引发的。您仍然没有发布异常文本,只发布了异常的类型。也许错误甚至不是来自那个动作? -
打开应用程序和 IoT Hub 之间的连接,但不是此行引发异常。
标签: c# asp.net-mvc azure-iot-sdk