Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use TIdHttp inside TThread anonymous function doesn't raise exceptions
#1
Hi all,

I am using a subclass of TIdHttp to expose DoRequest function. I use it in a tool similar to Rest Debugger so what I want to achieve regardless of the code because I can't show it. But I am pretty sure you will get the idea.

I use this new class inside a thread so I can handle files downloads and uploads with progress bars correctly without blocking the UI, and I do all the necessary synchronizations with the UI. My only problem is client side exceptions for example when I do a request and the server is not running nothing happens at all. Nothing is shown in the memo or as dialog message. I understand that this behaviour is because I am executing the request inside a thread. 

I want to catch any exception that was raised on the server with error code 500 inside a TMemo as long as any response message, and any exception that is not related to server side internal errors to be displayed normally in a dialog message box.

now this is not the actual code but it is similar:


Code:
__fastcall TIdHttpEx::TIdHttpEx(TComponent *Owner)
    : TIdHTTP(Owner)
{
HTTPOptions = TIdHTTPOptions() >> hoWantProtocolErrorContent;
FHTTPBody.reset(new TIdHTTPBody);
FHTTPBody->IdHTTP = this;

FHasErrorResponse = false;
FRaiseExceptionOn500 = true;
FLastErrorResponse = "";
}
//---------------------------------------------------------------------------
int __fastcall TIdHttpEx::DoExecute(String AMethod, String AURL, TStream* AResponseContent, TStream* ARequestContent)
{
try
    {
    FHasErrorResponse = false;
    FLastErrorResponse = "";

    if (FHTTPBody->RequestStream == nullptr && ARequestContent != nullptr)
        FHTTPBody->RequestStream = ARequestContent;

    if (FHTTPBody->ResponseStream == nullptr && AResponseContent != nullptr)
        FHTTPBody->ResponseStream = AResponseContent;

    if (FHTTPBody->ResponseStream == nullptr && AResponseContent == nullptr)
        FHTTPBody->ResponseStream = new TMemoryStream;

    DoRequest( AMethod, AURL, FHTTPBody->RequestStream, FHTTPBody->ResponseStream,nullptr,-1);

    FResponseOk = (ResponseCode == 200);

    if (FHTTPBody->ResponseStream != nullptr)
        FHTTPBody->ResponseStream->Position = 0;
    }
catch (const EIdHTTPProtocolException &E)
    {
    if (FRaiseExceptionOn500)
        throw Exception(E.ErrorMessage);
    else
        {
        FLastErrorResponse = E.ErrorMessage;
        FHasErrorResponse = (FLastErrorResponse.Trim() != "");
        DoHTTPErrorEvent(FLastErrorResponse);
        }
    }
catch (const Exception &E)
    {
    ShowException(&E, nullptr); //this do the trick but I don't know if it is the right thing to do
    }
}
Reply


Messages In This Thread
Use TIdHttp inside TThread anonymous function doesn't raise exceptions - by Ahmed Sayed - 09-02-2020, 01:20 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)