Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to handle response in RestSharp?

Tags:

c#

restsharp

I use RestSharp and I want to know what is the best way to handle response. There are ErrorMessage, ErrorException and ResponseStatus in RestResponse but how can I check whether request was successful?

I use this code. Does it look ok?

if (response.ResponseStatus != ResponseStatus.Completed)
{
    throw new ApplicationException(response.ErrorMessage);
}
like image 639
Pavel F Avatar asked Feb 11 '14 16:02

Pavel F


People also ask

How do you get a RestSharp response?

var client = new RestClient("http://myurl.com/api/"); var request = new RestRequest("getCatalog? token=saga001"); var queryResult = client. Execute(request); Console. WriteLine(queryResult);

What is the use of RestSharp?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.

Is RestSharp asynchronous?

RestSharp is an open-source HTTP Client library that we can use to consume APIs. Based on that, we can install it using NuGet Package Manager. Although RestSharp can call any API using the HTTP protocol, the purpose of RestSharp is to consume the REST APIs. RestSharp supports both synchronous and asynchronous requests.


1 Answers

This will not always catch all of the errors. As Jacob said, a ResponseStatus can have a value of Completed even if it returns a 404 or some other bad status.

Instead, use StatusCode which handles all of the HttpStatus responses.

if (response.StatusCode != System.Net.HttpStatusCode.OK)
  throw new ApplicationException(response.ErrorMessage);
like image 200
SMKS Avatar answered Sep 21 '22 07:09

SMKS