[英]How to deal with exception thrown by Web API controller?
I am using the Enterprise Tester API to import and update content on the web application. 我正在使用Enterprise Tester API导入和更新Web应用程序上的内容。 The program will work fine for a couple of hours but occasionally it runs into this unhandled exception:
该程序可以正常工作几个小时,但偶尔会遇到此未处理的异常:
An unhandled exception of type 'System.Net.Http.HttpRequestException' occurred in EnterpriseTester.API.Client.dll
EnterpriseTester.API.Client.dll中发生了类型为'System.Net.Http.HttpRequestException'的未处理异常
Additional information: System.Net.Http.HttpRequestException status code does not indicate success: 500 (Internal Server Error)
附加信息:System.Net.Http.HttpRequestException状态码不表示成功:500(内部服务器错误)
At this point, Visual Studio breaks at the line where this exception occurs. 此时,Visual Studio在发生此异常的行处中断。 However, when I click "Continue", the program will execute properly again.
但是,当我单击“继续”时,程序将再次正常执行。
From searching on the internet, it seems that I should use a try catch
block to handle the exception. 通过在互联网上搜索,似乎我应该使用
try catch
块来处理异常。 I also want to be able to wait a little bit and execute the same line again to access the API. 我还希望能够稍等片刻,然后再次执行同一行以访问API。
try
{
client.UpdateScriptRun(Id,Run);
}
catch (HttpRequestException e)
{
Console.Writeline("HttpRequestException: {0}", e.Message);
Thread.Sleep(1000);
client.UpdateScriptRun(Id,Run);
}
I am not sure if something like this would solve the issue or if I need to look into a completely different solution. 我不确定是否可以通过这种方式解决此问题,或者我是否需要研究完全不同的解决方案。
It would be much appreciated if you could guide me to a solution that seems fit to this problem. 如果您能指导我找到适合该问题的解决方案,将不胜感激。 Thank you!
谢谢!
Usually it's best to track down the root cause of the exception, and see if there's a way to fix it. 通常,最好跟踪异常的根本原因,并查看是否有解决方法。 It's one thing if there's a connection error that just happens because the network is having intermittent issues, but a 500 error indicates that something went wrong on the server.
如果只是由于网络间歇性问题而发生连接错误,那是一回事,但是500错误表明服务器上出现了问题。 If you have any way to track down and fix the server-side error, that's the best approach.
如果您有任何方法可以跟踪并修复服务器端错误,那是最好的方法。
If you have no control over the server, and are just trying to make your own app work as well as possible knowing that the server occasionally fails for no reason, then a try/catch solution will help. 如果您对服务器没有控制权,并且只是想让自己的应用程序正常工作,并且知道服务器偶尔会无故失败,那么尝试/捕获解决方案将有所帮助。 I'd make a few additional recommendations, though:
不过,我会提出一些其他建议:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.