0

How i can make the Idhttp run in loop if return 404 page not found the problem is 'GOTO CheckAgain' leads into or out of TRY statement

label
  CheckAgain;
begin  
  CheckAgain:
  try
    idhttp.Get(sURL+WebFile[I], S);
  except
    on E: EIdHTTPProtocolException do
    if AnsiPos('404',E.Message) <> 0 then
    begin
      I := I+1;
      goto CheckAgain;
    end;
  end;
end;
RepeatUntil
  • 2,272
  • 4
  • 32
  • 57
  • `while True do if ItsTimeToStop then Break;`, or just `while WantToTryAgain do Something;` P.S. do not parse the exception message; the `EIdHTTPProtocolException` exception has the `ErrorCode` member. – TLama Jun 12 '15 at 05:37
  • @TLama Thanks `while WantToTryAgain do Something` worked great, regarding the exception message `EIdHTTPProtocolException` i don't understand it – RepeatUntil Jun 12 '15 at 06:00
  • I meant that the `E` variable in your code context has also the `ErrorCode` member that contains the (already parsed) error code. More about it you might find e.g. in [`this thread`](http://stackoverflow.com/q/13950676/960757). – TLama Jun 12 '15 at 06:09

2 Answers2

3

You have three options:

  1. use a try/except block in a loop, catching EIdHTTPProtocolException exceptions and checking their ErrorCode property for 404:

    repeat
      try
        IdHttp.Get(sURL+WebFile[I], S);
      except
        on E: EIdHTTPProtocolException do
        begin
          if E.ErrorCode <> 404 then
            raise;
          Inc(I);
          Continue;
        end;
      end;
      Break;
    until False;
    
  2. if you are using an up-to-date version of Indy, you can enable the hoNoProtocolErrorException flag in the TIdHTTP.HTTPOptions property, and then your loop can remove the try/except and check the TIdHTTP.ResponseCode property instead:

    repeat
      IdHttp.Get(sURL+WebFile[I], S);
      if IdHttp.ResponseCode <> 404 then
        Break;
      Inc(I);
    until False;
    
  3. use the overloaded version of the TIdHTTP.Get() method that has an AIgnoreReplies parameter, then you can tell Get() to not raise an EIdHTTPProtocolException exception on a 404 response:

    repeat
      IdHttp.Get(sURL+WebFile[I], S, [404]);
      if IdHttp.ResponseCode <> 404 then
        Break;
      Inc(I);
    until False;
    
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

As a general rule, I'd avoid using goto. There are occasions where goto should be used, but they are rare and your problem is not suited.

A while loop would be more commonly used. You'd be able to build in a maximum retry mechanism too. Perhaps like this:

RetryCount := 0;
Succeeded := False;
while RetryCount < MaxRetryCount do
  try
    idhttp.Get(sURL+WebFile[I], S);
    Succeeded := True;
    break; // success, break out of while loop
  except
    on E: EIdHTTPProtocolException do
      if E.ErrorCode = 404 then
        inc(RetryCount)
      else
        raise;

  end;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490