gpt4 book ai didi

c# - 无法在 ASP.NET MVC 中捕获异常

转载 作者:行者123 更新时间:2023-11-30 16:40:43 24 4
gpt4 key购买 nike

我目前正在尝试为我的 IoT 学校项目开发简单的 Web 应用程序。至于现在,它应该只从我的 Raspberry 调用直接方法。我正在使用适用于 C# 的 Azure SDK。

代码是这样的:

Controller :

    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 block 处理。

console output

    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).

谁能告诉我如何在我的应用程序中捕获和处理这个异常?预先感谢您的回答。

最佳答案

我不确定错误输出实际上是抛给您的代码的异常。它可能只是 ApplicationInsights 的日志记录。 但是,我认为代码由于调用 Wait 而被卡住并阻止异步方法的返回。

使 Controller 方法返回类型 Task<ActionResult> ,使该方法async , 然后使用 await c2d.EnableRaspberry("myDeviceId");调用该方法。

看看这样做是否会导致异常(或成功)。

关于c# - 无法在 ASP.NET MVC 中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50584193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com