gpt4 book ai didi

error-handling - RestSharp GetAsync忽略响应错误状态码

转载 作者:行者123 更新时间:2023-12-03 08:44:11 27 4
gpt4 key购买 nike

RestSharp的GetAsync<>方法的注释明确提到:

Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.



我不确定如何解释。我希望它在返回不成功的HTTP状态代码时引发异常。似乎并非如此。当返回404或500状态时,该方法会愉快地尝试反序列化响应。仅当响应正文包含无效的json(或xml或“已接受”的任何内容)时,才会引发错误。

我想念什么吗?我应该如何使用这些异步方法处理此类错误响应?

最佳答案

这种行为也使我失望。

查看RestClientExtensions at GitHub的源代码,GetAsync方法实现为:

public static async Task<T> GetAsync<T>(this IRestClient client, IRestRequest request, CancellationToken cancellationToken = default)
{
var response = await client.ExecuteGetAsync<T>(request, cancellationToken);
ThrowIfError(response);
return response.Data;
}

您可能希望 ThrowIfError会查看HTTP状态代码,但会看到 RestSharp documentation for error handling,它说:

If there is a network transport error (network is down, failed DNS lookup, etc), RestResponse.ResponseStatus will be set to ResponseStatus.Error, otherwise it will be ResponseStatus.Completed.

If an API returns a 404, ResponseStatus will still be Completed.



您可以通过查看 ThrowIfError实现来确认:
static void ThrowIfError(IRestResponse response)
{
var exception = response.ResponseStatus switch
{
ResponseStatus.Aborted => new WebException("Request aborted", response.ErrorException),
ResponseStatus.Error => response.ErrorException,
ResponseStatus.TimedOut => new TimeoutException("Request timed out", response.ErrorException),
ResponseStatus.None => null,
ResponseStatus.Completed => null,
_ => throw response.ErrorException ?? new ArgumentOutOfRangeException()
};

if (exception != null)
throw exception;
}

至于你的问题:

How should I, using these async methods, handle such error responses?



你不能:(。

我相信您将必须实现自己的 Get<T>异步实现。

这是我所做的一个示例:
private Task<T> GetAsync<T>(RestRequest request)
{
return Task.Run(() =>
{
var response = client.Get<T>(request);
if (response.IsSuccessful)
return response.Data;

//handle the errors as you wish. In my case, the api I work with always
//returns a bad request with a message property when it occurs...
var errorData = JsonConvert.DeserializeObject<ApiMessage>(response.Content);
throw new Exception(errorData.Message);
});
}

public class ApiMessage
{
public string Message { get; set; }
}

用法:
public Task<MyModel> SomeRequest()
{
var request = new RestRequest()
{
Resource = "some-resource",
};

return GetAsync<MyModel>(request);
}

资源:

关于error-handling - RestSharp GetAsync忽略响应错误状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58536796/

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