-2

我有一个连接到 API 的函数。有时 API 不可用。我知道为什么,但我想防止我的程序在这种情况下崩溃。但无论我尝试什么,它总是崩溃:

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

我想记录一条错误消息,然后程序继续而不是崩溃。有人可以指出我正确的方向吗?

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);
        }
    }
4

1 回答 1

1

您正在捕获 System.Net.Sockets.SocketException,但正在引发 System.Net.WebException

于 2020-10-20T14:07:47.703 回答