0

こんにちは、私は Delphi を使用するのが初めてで、Web サイトが稼働しているかどうか、または何か問題があるかどうかを確認するアプリケーションを作成しようとしています。Indy の IdHTT を使用しています。問題は、プロトコル エラーは検出されますが、ソケット エラーなどは検出されないことです。

procedure TWebSiteStatus.Button1Click(Sender: TObject);
  var
    http : TIdHTTP;
    url : string;
    code : integer;
  begin
     url := 'http://www.'+Edit1.Text;
     http := TIdHTTP.Create(nil);
     try
       try
         http.Head(url);
         code := http.ResponseCode;
       except
         on E: EIdHTTPProtocolException do
           code := http.ResponseCode; 
         end;
         ShowMessage(IntToStr(code));
         if code <> 200 then
         begin
           Edit2.Text:='Something is wrong with the website';
           down;
         end;
     finally
       http.Free();
     end;
  end;

私は基本的に、ウェブサイトが正常ではないことをキャッチしようとしているので、別のフォームを呼び出して、サイトがダウンしていることを知らせる電子メールをセットアップできます。

更新:最初にあなたは正しいです私は「それから」申し訳ありませんが他のコードを削除していたことを見逃していましたが、誤って削除されました。例外を処理するときの一般的な特定を知りませんでした。最後に、私が探していたのはこのコードであることがわかりました

on E: EIdSocketError do    

uses IdStack の使用

4

1 に答える 1

5

コードを変更して、すべての例外をキャッチするか、より具体的な例外も追加します。

url := 'http://www.'+Edit1.Text;
http := TIdHTTP.Create(nil);
try
  try
    http.Head(url);
    code := http.ResponseCode;
  except
    on E: EIdHTTPProtocolException do
    begin
      code := http.ResponseCode; 
      ShowMessage(IntToStr(code));
      if code <> 200 
      begin
        Edit2.Text:='Something is wrong with the website';
        down;
      end;
    end;
    // Other specific Indy (EId*) exceptions if wanted
    on E: Exception do
    begin
      ShowMessage(E.Message);
    end;
  end;  // Added missing end here.
finally
  http.Free();
end;

複数の例外タイプを処理する場合は、最も具体的なものから最も具体的でないものへと進むことが重要であることに注意してください。つまり、特定性の低い (より一般的なタイプの) 例外を最初に配置すると、次のようになります。

try
  DoSomethingThatCanRaiseAnException();
except
  on E: Exception do
    ShowMessage('This one fires always (covers all exceptions)');
  on E: EConvertError do
    ShowMessage('This one will never happen - never gets this far');
end;

これは、具体的でないものに対してより具体的であるため、適切に機能します。正しくは、逆になります。

try
  DoSomethingThatCanRaiseAnException();
except
  on E: EConvertError do
    ShowMessage('This one gets all EConvertError exceptions');
  on E: Exception do
    ShowMessage('This one catches all types except EConvertError');
end;
于 2013-10-08T20:33:44.003 に答える