A typical http call using RestSharp looks as follows:
var client = new RestClient("http://exampleapi.com");
var request = new RestRequest("someapi", Method.GET);
IRestResponse response = client.Execute(request);
From the documentation at https://github.com/restsharp/RestSharp/wiki/Getting-Started:
If there is a network transport error (network is down, failed DNS lookup, etc), RestResponse.Status will be set to ResponseStatus.Error, otherwise it will be ResponseStatus.Completed. If an API returns a 404, ResponseStatus will still be Completed. If you need access to the HTTP status code returned you will find it at RestResponse.StatusCode.
Further, the following appear to be behaviors of RestSharp responses:
- RestClient.Execute() will never throw an exception
- If the network request fails, ie a condition occurs that would normally result in an exception (eg network timed out, unreachable, name could not be resolved), then
response.ErrorException
will be populated with some Exception-derived type andresponse.ErrorMessage
will contain some message error string andresponse.StatusCode
will be set toResponseStatus.Error
,Response.Status.Aborted
,ResponseStatus.TimedOut
, etc. - If the network request succeeds but there's some HTTP error (eg 404 not found, 500 server error, etc.), then
response.StatusCode
will be set toNotFound
, etc,Response.ErrorException
andResponse.Error
will benull
andresponse.StatusCode
will be set to 'ResponseStatus.Completed`.
I may have missed some possible responses, but I think the gist is there.
Given this, how should I determine response success or failure? Options include:
- If
ErrorException == null
then check the http response - If
response.ResponseStatus == ResponseStatus.Completed
then check Response.StatusCode and depending on the result, grab the response data and handle accordingly if not what you expect - If the http response is some error then depending on the type of error check
ErrorException
- More...?
I don't want to overthink this but I am assuming there's a pattern (for lack of better term) for handling this cleanly.