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

标签 error-handling restsharp http-status-codes

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/

相关文章:

error-handling - RX2.0嵌套订阅错误处理

php - 在 php 中系统化 web 应用程序的错误代码?

c# - 覆盖扩展方法 C#

C# Web 请求 w RestSharp - "The request was aborted: Could not create SSL/TLS secure channel"

rest - 拒绝不受支持的 API 客户端时的 HTTP 状态代码

http-status-codes - 如何使用 Micronaut 客户端接受自定义 HTTP 错误代码?

wcf - 导致在 WCF 中返回 HTTP 错误状态

python - 使用try/except然后在类中抛出一个方法

excel - 如何使用Application.WorksheetFunction.Match捕获错误并进行处理?

c# - 错误提示:找不到方法:“无效RestSharp.RestClient.set_BaseUrl(System.String)”。在特维里奥沙普