简体   繁体   中英

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

Additional information: System.Net.Http.HttpRequestException status code does not indicate success: 500 (Internal Server Error)

At this point, Visual Studio breaks at the line where this exception occurs. 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. I also want to be able to wait a little bit and execute the same line again to access the 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. 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:

  1. Use a more robust logging mechanism, so you can tell from your log files how often things are going wrong, and maybe use that information to track down issues. Include the parameters in your log message, in case that information turns out to be useful.
  2. Create a helper method to help you with your retries, so you can reuse the pattern elsewhere.
  3. In this helper method, start by retrying almost immediately, and then wait an exponentially increasing period of time (10ms, 100ms, 1000ms) until you either see success or hit a reasonable maximum limit.
  4. Whatever is consuming your code should have its own try/catch to ensure that the user has a decent experience when things aren't working right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM