fabriciocolombo / delphi-rest-client-api

A Delphi REST client API to consume REST services written in any programming language.
Apache License 2.0
380 stars 182 forks source link

Adds OnResponse event and allows overriding which response code throws exception #81

Closed fabioxgn closed 7 years ago

fabioxgn commented 7 years ago

I'm integrating with an API that returns 422 when there's a validation error and a JSON with the errors, the current behaviour will raise an exception with this code which does not allow me to handle the errors correctly.

To not break compatibility with current code, I've implemented a virtual method so I can override it and do not raise an exception when the response code is 422 (Unprocessable Entity).

Also, I wanted to add some logs (to capture the response content), so I've implemented a New OnResponse event, that allows that.

thomaserlang commented 7 years ago

Just FYI. You can use TRestClient.OnError event to control what happens on status codes above or equal to 400. Just set ARetryMode to hrmIgnore. You can even use hrmRetry if you want it to retry the request.

Example:

restclient := TRestClient.Create(self); 
restclient.ConnectionType := hctWinINet;
restclient.OnError := RestError;

procedure Tdm.RestError(ARestClient: TRestClient; AResource: restclient.TResource;
  AMethod: TRequestMethod; AHTTPError: EHTTPError;
  var ARetryMode: THTTPRetryMode);
begin
  ARetryMode := hrmRaise;
  if AHTTPError.ErrorCode = 422 then
    ARetryMode := hrmIgnore;
end;
fabioxgn commented 7 years ago

@thomaserlang the problem with that is that if I set hrmIgnore the result is cleared.

else if vRetryMode = hrmRetry then
        result := DoRequest(Method, ResourceRequest, AHandler)
      else
        result := '';

And in my case, when there's a 422 I must read the response to read the errors.

I didn't want to change this behavior, that's why I implemented this virtual method. I think that the result is cleared to avoid errors trying to parse the response when the server returns an html for example.

If you have any suggestions, please let me know.

thomaserlang commented 7 years ago

Ah, ok.