问题描述
我有一个连接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);
}
}
解决方法
您正在捕获System.Net.Sockets.SocketException,但正在抛出System.Net.WebException