Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch exceptions with RestSharp [closed]

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.

like image 231
okeziestanley Avatar asked Jul 04 '15 16:07

okeziestanley


People also ask

Is RestSharp better than HttpClient?

The main conclusion is that one is not better than the other, and we shouldn't compare them since RestSharp is a wrapper around HttpClient. The decision between using one of the two tools depends on the use case and the situation.

Is RestSharp asynchronous?

RestSharp v107 changes the library API surface and its behaviour significantly. We advise looking at v107 docs to understand how to migrate to the latest version of RestSharp. The main purpose of RestSharp is to make synchronous and asynchronous calls to remote resources over HTTP.

How do I request a RestSharp body?

The request body is a type of parameter. To add one, you can do one of these... req. AddBody(body); req.

How do you handle multiple types of exceptions at once?

They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the Chained Exceptions section. You can catch more than one type of exception with one exception handler, with the multi-catch pattern.

Should I use exception in try catch block?

In general, don't specify Exception as the exception filter unless either you know how to handle all exceptions that might be thrown in the try block, or you've included a throw statement at the end of your catch block. Multiple catch blocks with different exception classes can be chained together.

How do you handle an exception in a throwable?

The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name. The catch block contains code that is executed if and when the exception handler is invoked.

How to partially handle an exception before passing it on?

You want to partially handle an exception before passing it on for more handling. In the following example, a catch block is used to add an entry to an error log before rethrowing the exception. try { // Try to access a resource. } catch (UnauthorizedAccessException e) { // Call a custom error logging procedure.


1 Answers

#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

like image 55
Terrance Avatar answered Sep 18 '22 22:09

Terrance