Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp - How to handle non-200 responses? RestClient throws exception on Execute

I'm using RestSharp in Windows Phone 8.1 application. RestClient throws exception when server returns response with code different than 200. Wiki says that I should get response with correct status code. I want to get content of response because server returns error messages.

private async Task<T> ExecuteAsync<T>(IRestRequest request)
    {
        if (!_networkAvailableService.IsNetworkAvailable)
        {
            throw new NoInternetException();
        }

        request.AddHeader("Accept", "application/json");

        IRestResponse<T> response;
        try
        {
            response = await _client.Execute<T>(request); //here I get exception
        }
        catch (Exception ex)
        {
            throw new ApiException();
        }

        HandleApiException(response);

        return response.Data;
    }

    private void HandleApiException(IRestResponse response)
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            return;
        }
//never reach here :( 
        ApiException apiException;
        try
        {
            var apiError = _deserializer.Deserialize<ApiErrorResponse>(response);
            apiException = new ApiException(apiError);
        }
        catch (Exception)
        {
            throw new ApiException();
        }

        throw apiException;
    }

sample of server response:

HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 86
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Date: Mon, 28 Sep 2015 12:30:10 GMT
Connection: close

{"error":"invalid_token","error_description":"The user name or password is incorrect"}
like image 744
Tomasz Pikć Avatar asked Oct 21 '25 11:10

Tomasz Pikć


1 Answers

If you are working under Windows Phone 8.1, you're using RestSharp Portable (https://github.com/FubarDevelopment/restsharp.portable) (probably). Use this:

var client = new RestClient();
client.IgnoreResponseStatusCode = true;

With this, you don't get exception with 404 for example. I hope it will be helpful :)

like image 172
Arek Kubiak Avatar answered Oct 23 '25 01:10

Arek Kubiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!