Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indy and REST - Can I prevent exceptions?

Is there a way to prevent Indy from raising exceptions on any/all HTTP statuses?

My understanding of the IgnoreReplies array is that it'll prevent those statuses from ever coming back, but that's not what I want. I want ALL statuses coming back, and none of them to raise an exception. There are plenty of REST services that return 404 for example, and that's considered a perfectly "valid" response.

I really don't want 1/2 of my code in exception handlers, so is there way to get the current Indy to just return everything?

like image 772
DaveS_Lifeway Avatar asked Feb 21 '13 22:02

DaveS_Lifeway


1 Answers

Sorry, but you have to use the IgnoreReplies parameter to tell TIdHTTP which specific HTTP reply codes to not raise an exception for. There is currently no way to tell TIdHTTP to not raise an exception for all possible replies generically. If you want to receive a non-success reply, like 404, without raising an exception then you have to tell TIdHTTP that, eg:

IdHTTP.Get('http://host/path', [404]);

Note that this syntax is only available for GET requests, not other requests, like POST (unless you call the protected TIdHTTP.DoRequest() method directly).

Indy is specifically designed around exception handling. You have to embrace exceptions, not avoid them, if you want to use Indy effectively. What is so troublesome about wrapping TIdHTTP.Get() or TIdHTTP.Post() in a small try/except block? If you don't want to handle all possible exceptions, then you can have the except block handle EIdHTTPProtocolException by itself.

try
  IdHTTP.Get('http://host/path');
except
  on E: EIdHTTPProtocolException do
  begin
    if E.ErrorCode <> 404 then Raise;
  end;
end;

Update: thinking about it more, it might be worth adding a new flag to the TIdHTTP.HTTPOptions property to disable the exception for all status codes. I'm considering it.

Update: a new hoNoProtocolErrorException flag has now been added to the TIdHTTP.HTTPOptions property:

IdHTTP.HTTPOptions := IdHTTP.HTTPOptions + [hoNoProtocolErrorException];
IdHTTP.Get('http://host/path');
// use IdHTTP.ResponseCode as needed...

Update: in addition, there is also a hoWantProtocolErrorContent flag as well. When hoNoProtocolErrorException is enabled and an HTTP error occurs, if hoWantProtocolErrorContent is enabled then the error content will be returned to the caller (either in a String return value or in an AResponseContent output stream, depending on which version of Get()/Post() is being called), otherwise the content will be discarded.

like image 120
Remy Lebeau Avatar answered Sep 30 '22 18:09

Remy Lebeau