2015-09-28 31 views
2

我在Windows Phone 8.1應用程序中使用RestSharp。當服務器返回代碼不是200的響應時,RestClient拋出異常。Wiki說我應該得到正確的狀態碼。我想獲得響應的內容,因爲服務器返回錯誤消息。服務器響應的RestSharp - 如何處理非200響應? RestClient在執行時拋出異常

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

回答

7

如果您在Windows Phone的8.1工作,您正在使用RestSharp便攜式(https://github.com/FubarDevelopment/restsharp.portable)(可能)。 使用此:

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

有了這個,你不404例如獲得例外。 我希望這會有所幫助:)

+0

的確如此。使用普通的RestSharp這不會發生。在使用RestSharp Portable時,您需要按照上文所述配置您的客戶端!對於Xamarin使用的PCL組件,這必須完成。 – John

相關問題