RestSharp-如何处理非200响应?RestClient在Execute上引发异常 [英] RestSharp - How to handle non-200 responses? RestClient throws exception on Execute

查看:59
本文介绍了RestSharp-如何处理非200响应?RestClient在Execute上引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows Phone 8.1应用程序中使用RestSharp.服务器返回的响应代码不同于200时,RestClient会引发异常. Wiki 说,我应该获得正确的状态码响应.我想获取响应的内容,因为服务器返回了错误消息.

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;
    }

服务器响应示例:

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"}

推荐答案

如果您在Windows Phone 8.1下工作,则使用的是RestSharp Portable(

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;

例如,您不会在404中遇到异常.希望对您有所帮助:)

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

这篇关于RestSharp-如何处理非200响应?RestClient在Execute上引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆