【问题标题】:RestSharp - How to handle non-200 responses? RestClient throws exception on ExecuteRestSharp - 如何处理非 200 响应? RestClient 在执行时抛出异常
【发布时间】:2015-09-29 00:46:03
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net windows-phone-8.1 win-universal-app restsharp


    【解决方案1】:

    如果您在 Windows Phone 8.1 下工作,那么您正在使用 RestSharp Portable (https://github.com/FubarDevelopment/restsharp.portable)(可能)。 使用这个:

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

    有了这个,例如 404 就不会出现异常。 我希望它会有所帮助:)

    【讨论】:

    • 确实如此。使用普通的 RestSharp 不会发生这种情况。使用 RestSharp Portable 时,您需要如上所述配置您的客户端!对于与 Xamarin 一起使用的 PCL 程序集,必须执行此操作。
    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 2012-03-30
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多