TIdHTTP异常处理

Cor*_*ver 1 delphi indy10 delphi-xe2

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

// 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;
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

Rem*_*eau 11

您的异常处理程序仅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;
Run Code Online (Sandbox Code Playgroud)

  • 您可以找到更多关于`TIdHTTP`例外的内容[`here`](http://stackoverflow.com/a/13954599/960757).[1] (5认同)