TIdHTTP异常处理

时间:2013-04-28 22:55:23

标签: delphi delphi-xe2 indy10

我创建了一个自动连接到本地服务器并下载更新的程序,代码如下:

// Connect to web server and download ToBeInstalled.ini
Url := 'http://'+IPAdd+'/ToBeInstalled.ini';
MS := TMemoryStream.Create
  try
    try
      http.Get(url, MS);
      code := http.ResponseText;
    except
      on E: EIdHTTPProtocolException do
        code := http.ResponseCode; 
    end;
    MS.SaveToFile(UserPath + 'ToBeInstalled.ini');
  finally
    http.Free();
  end;

该程序在办公室工作得很好,但当用户在家但无法访问服务器或服务器不可用时,获取“套接字错误#10061”

enter image description here

我不知道如何捕获那个,更糟糕的是程序在显示错误消息后一起停止执行。你知道如何解决这个问题吗?非常感谢你。

1 个答案:

答案 0 :(得分:10)

您的异常处理程序仅具体捕获EIdHTTPProtocolException个异常,但也可以引发其他几种类型的异常,包括EIdSocketError。您需要相应地更新处理程序,或者让它捕获所有可能的异常,而不是查找特定类型。既然你说一个未被捕获的异常导致你的整个应用程序失败(这意味着你有更大的问题要处理而不仅仅是TIdHTTP),你也应该更新代码来处理TMemoryStream引发的异常。

试试这个:

// Connect to web server and download ToBeInstalled.ini
Url := 'http://'+IPAdd+'/ToBeInstalled.ini';
try
  MS := TMemoryStream.Create
  try
    http.Get(url, MS);
    code := http.ResponseText;
    MS.SaveToFile(UserPath + 'ToBeInstalled.ini');
  finally
    MS.Free;
  end;
except
  on E: EIdHTTPProtocolException do begin
    code := http.ResponseCode; 
  end;
  on E: Exception begin
    // do something else
  end;
end;
相关问题