1

I cannot seem to catch HttpRequestException or any exception for that matter when sending request to a nonexistent endpoint.

http://localhost:8030/ does not exist, however I should be able to catch HttpRequestException in try/catch block. What am I missing ?

            Uri address = new Uri("http://localhost:8030/");
            HttpClient client = new HttpClient();
            var rm = new HttpRequestMessage()
            {
                Method = HttpMethod.Post,
                RequestUri = address
            };

            try
            {
                var response = await client.SendAsync(rm);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

VSscreenshot

Kirill
  • 11
  • 1
  • Does it "catch" your exception if you run it outside the debugger? – mxmissile Feb 16 '21 at 21:09
  • This is being caught, however, you are seeing a debugging feature. If you press continue you will likely see it hit the catch – TheGeneral Feb 16 '21 at 21:20
  • In the Debug > Exceptions dialog, click Add, select Common Language Runtime exceptions, and enter the full name of the exception. Then uncheck the Thrown checkbox for this exception. – TheGeneral Feb 16 '21 at 21:21
  • @mxmissile It worked thank you, but how is this a feature ? Why is it behaving differently ? – Kirill Feb 16 '21 at 21:39
  • Disable "Just My Code" in your debugger settings, more info here: https://stackoverflow.com/questions/19865523/why-cant-i-catch-an-exception-from-async-code – mxmissile Feb 16 '21 at 21:47
  • Because, the designers thought by default some exceptions might be useful to know at runtime in debug, so you can inspect variables and state before the stack completely unwinds. You can switch this off multiple ways, its as easy as that – TheGeneral Feb 16 '21 at 22:19
  • You can also change it directly in the exception dialog "Break when this exception type is thrown" – pinkfloydx33 Feb 16 '21 at 22:36

0 Answers0