1

I want to call an external Api in my application and after calling the Api if a timeout exception throws then my app returns a result. Now I want to simulate this situation. this is my code :

 public string Sample()
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response =
                    client.GetAsync("ExternalApi").GetAwaiter().GetResult();
                //...
            }
        }
        catch (Exception e)
        {
            return ((HttpRequestException) e).StatusCode == HttpStatusCode.RequestTimeout ? "timeOut" : "Error";
        }

        return "Success";
    }

If I throw a TimeoutException in ExternalApi then in Sample method I get Internal server error. How to create an artificial timeout exception?

Nega
  • 119
  • 8

4 Answers4

1

The HttpClient class has a Timeout attribute.

So try this.

using (HttpClient client 
     = new HttpClient(){Timeout=new TimeSpan(0,5,0)})

for a five minute timeout.

If the timeout expires you'll get a WebException.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
1

For this purpose, I finally use an application called 'Hercules Setup Utility'. This application listens to a port in 'Tcp Server' and get your request but doesn't respond at all. After executing this app and listening to a port, you have to set something like localhost:port in your app. You will get a timeout exception.

Nega
  • 119
  • 8
1

The HttpClient class has a Timeout attribute. Or you can use some apps to create timeout like Hercules Setup Utility

Programmer
  • 75
  • 5
-1

I recently did an alternative to Tracert using a Task method so as to get an exception if something goes wrong sending a request for DNS info. I guess that you should use Task<>. Take a look at the main MSDN explanation :

https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=net-5.0

Also I think that you could appreciate how I check success or exception in my own code. Take a look at the code inside the boolean DNS check :

An alternative class for Tracert with DNS feature