gpt4 book ai didi

c# - RestSharp - 如何处理非 200 响应? RestClient 在执行时抛出异常

转载 作者:行者123 更新时间:2023-11-30 14:08:52 25 4
gpt4 key购买 nike

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

最佳答案

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

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

这样,您就不会遇到 404 等异常。希望对您有所帮助:)

关于c# - RestSharp - 如何处理非 200 响应? RestClient 在执行时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32824075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com