How can I catch exceptions with RestSharp

okeziestanley picture okeziestanley · Jul 4, 2015 · Viewed 22.6k times · Source

I am working on a project with RestSharp. Over time I discovered several exceptions that RestResponse class can throw, most of which I have to handle so my app doesn't crash. How can I know of all possible exceptions and handle them individually.

Answer

Terrance picture Terrance · Aug 10, 2015

#RestResponses and Errors#

This is from the docs at RestSharp's wiki

##Note about error handling## **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. The Status property is an indicator of completion independent of the API error handling.

That being said the recommended way to check the status of the RestResponse is to look at RestResponse.Status

The source itself for the internal Execute call reads as follows.

private IRestResponse Execute(IRestRequest request, string httpMethod,Func<IHttp, string, HttpResponse> getResponse)
{
    AuthenticateIfNeeded(this, request);
    IRestResponse response = new RestResponse();
    try
    {
        var http = HttpFactory.Create();

        ConfigureHttp(request, http);

        response = ConvertToRestResponse(request, getResponse(http, httpMethod));
        response.Request = request;
        response.Request.IncreaseNumAttempts();

    }
    catch (Exception ex)
    {
        response.ResponseStatus = ResponseStatus.Error;
        response.ErrorMessage = ex.Message;
        response.ErrorException = ex;
    }

    return response;
}

So with that, you know that you can expect standard .net exceptions. The recommended usage suggests just checking for the existence of an ErrorException like in the code example.

//Snippet of code example in above link
var response = client.Execute<T>(request);

if (response.ErrorException != null)
{
    const string message = "Error retrieving response.  Check inner details for more info.";
    var twilioException = new Exception(message, response.ErrorException);
    throw twilioException;
}

If you want to preform a specific action on a certain kind of exception just preform a type comparison using a line like the following.

if (response.ErrorException.GetType() == typeof(NullReferenceException))
{
  //handle error
}

How can I know of all possible exceptions and handle them individually.

Honestly, I'd recommend against catching all the exceptions individually and I'd find that particular requirement questionable. Are you sure they don't just want you to catch and handle exceptions gracefully?

If you absolutely need to handle each possible case individually then I'd log the exceptions that crop up in testing and check against those. If you were to try and catch everything you could potentially have over a hundred different exceptions. That is what the base Exception class is for.

The exception class is the catch-all for handling anything that inherits from Exception. The general idea is that you make special note of the exceptions that you can actually do something with like notifying the user that the internet is unavailable or the remote server is down and let the exception class handle any other edge cases. msdn link