Search code examples
androiddelphiexceptionfiremonkeyidhttp

IdHTTP Exception Causes Segmentation Fault


I have run the code below as an Android App. The lHttp sends an request to a WebService that i made, where the IP (URL) and Port are defined by the user. However, if the webservice is not active in that URL the App is crashed. While debugging, it gives me the following errors while trying to catch an exception.

raised exception class EIdHTTPProtocolException with message 'HTTP/1.1 500 Internal Server Error'.
raised exception class Segmentation fault (11).
raised exception class EAccessViolation with message 'Access violation at address B6FBD7CE, accessing address 000000A8'.

Does someone know how to catch this exception whithout crashing the App?

  Path:= 'http://'+ Conf.IP + ':' + Conf.Port +'/services/MyWebService.dll/GetQuestions';

  lHTTP:= TIdHTTP.Create(nil);

  Stream:= TStringStream.Create;
  Stream.WriteString(Requisition);

  try
    Result := lHTTP.Post(Path, Stream);
  except
    on E:EIdException do
      Result:= E.Message;

    on E:EIdSocketError do
      Result:= E.Message;

    on E:EIdConnClosedGracefully do
      Result:= E.Message;

    on E:EIdHTTPProtocolException do
      Result:= E.Message;

    on E:Exception do
      Result:= E.Message;
  end;

  Stream.Free;

  FreeAndNil(lHTTP);

Solution

  • I'm not sure of what you are actually asking for: solving 500 ISE or catching the exception, but I'm going with:

    Does someone know how to catch this exception whithout crashing the App?

    Answer: You can create a global exception handler.

    1- Declare your custom exception handler in your form's "public declarations" section. For example, if your form is named "Form1:"

    { Public declarations }
    procedure MyExceptionHandler(Sender : TObject; E : Exception );
    

    2 - Define your exception handler in the "implementation" section:

    procedure TForm1.MyExceptionHandler(Sender : TObject; E : Exception );
    begin
    
        if E.Message.Contains('HTTP/1.1 500 Internal Server Error') then
        begin
        // Do Something
        end;
    
        {
        // Default App Exception
        Application.ShowException( E );
        }
    
            end;
    

    3 - Finally, assign the newly created exception handler to your application's OnException event.

    procedure
      TForm1.FormCreate(Sender: TObject);
    begin
      { begin new code }
      Application.OnException :=
        MyExceptionHandler;
      { end new code }
    end;