-2

I have a function where I connect to an API. Sometimes the API is not available. I know why but I would like to prevent my program from crashing when this is the case. But whatever I try it always crashes with:

Exception Unhandled 
System.Net.WebException: 'Unable to connect to the remote server'
SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:1000

I would like to log an error message and then the program to continue instead of crashing. Can someone please point me in the right direction?

static public void ConnectToAPI(string urlstring, string json, string command)
    {
        WebRequest request = WebRequest.Create(urlstring);
        request.Method = command;
        byte[] requestBody = Encoding.UTF8.GetBytes(json);
        request.ContentLength = requestBody.Length;
        request.ContentType = "application/json";
        try
        {
            using (Stream stream = request.GetRequestStream())
        }
        catch (System.Net.Sockets.SocketException exception)
        {
            log.Error(exception);
        }
    }
  • 1
    Uh, have you tried changing the exception type in your catch clause? Or adding an additional catch for the type? – gunr2171 Oct 20 '20 at 14:04

1 Answers1

1

You're catching a System.Net.Sockets.SocketException, but a System.Net.WebException is being thrown

DavidB
  • 2,566
  • 3
  • 33
  • 63
  • Thanks, that was helpfull. So I changed to this which works: ``` catch (System.Net.WebException e) { Console.WriteLine(e.Message); } ``` – Leonard Oct 20 '20 at 14:10