Nerdtron
Nerdtron

Reputation: 1516

de-serialization of response when the request may return different objects

I'm using RestSharp to invoke an API. I have the basic functionality working pretty well now, I can call RestClient.Execute(new RestRequest("/something")). The server returns JSON which is mapped over to a class I created. This all works great.

However... if the call fails, the server will return a different object. It returns an error object on failure which, of course, won't match the type specified for success.

Is there a way to deal with a request which may either return the normal answer or an error object?

Upvotes: 1

Views: 540

Answers (1)

Nerdtron
Nerdtron

Reputation: 1516

Got it working. What I'm seeing is that if the call fails, IRestResponse.IsSuccessful is false and the response content JSON string is the error object instead of the normal response.

So, after calling RestClient.Execute, if IsSuccessful is false, I then call RestClient.Deserialize using an error object C# class.

In this way if the call succeeds, I get the regular de-serialized object, if the call fails, I get the API's error object which I can then throw as an exception or otherwise handle.

Upvotes: 1

Related Questions