处理RestSharp错误响应的正确策略是什么?

Rob*_*ert 14 c# error-handling exception http restsharp

使用RestSharp的典型http调用如下所示:

var client = new RestClient("http://exampleapi.com");
var request = new RestRequest("someapi", Method.GET);
IRestResponse response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

来自https://github.com/restsharp/RestSharp/wiki/Getting-Started上的文档:

如果存在网络传输错误(网络中断,DNS查找失败等),则RestResponse.Status将设置为ResponseStatus.Error,否则将为ResponseStatus.Completed.如果API返回404,则ResponseStatus仍将完成.如果您需要访问返回的HTTP状态代码,您可以在RestResponse.StatusCode中找到它.

此外,以下似乎是RestSharp响应的行为:

  • RestClient.Execute()永远不会抛出异常
  • 如果网络请求失败,即发生通常会导致异常的情况(例如网络超时,无法访问,名称无法解析),response.ErrorException则将填充一些Exception派生类型,response.ErrorMessage并将包含一些消息错误字符串和response.StatusCode将被设置为ResponseStatus.Error,Response.Status.Aborted,ResponseStatus.TimedOut,等.
  • 如果网络请求成功,但有一些HTTP错误(如404未找到,500服务器错误等),然后response.StatusCode将设置NotFound等,Response.ErrorExceptionResponse.Errornullresponse.StatusCode将被设置为"ResponseStatus.Completed`.

我可能错过了一些可能的回应,但我认为要点就在那里.

鉴于此,我应该如何确定响应的成功或失败?选项包括:

  • 如果ErrorException == null那么检查http响应
  • 如果response.ResponseStatus == ResponseStatus.Completed然后检查Response.StatusCode并根据结果获取响应数据并相应处理,如果不是您期望的
  • 如果http响应有些错误,那么取决于错误检查的类型 ErrorException
  • 更多...?

我不想过分反思这一点,但我假设有一个模式(缺乏更好的术语)来干净利落地处理这个问题.

Sem*_*nda 1

我认为响应代码是 HttpStatusCode 类型。所以你可以获得如下代码。我想在那之后你就知道如何处理它了。

RestResponse response = client.Execute(request);
HttpStatusCode statusCode = response.StatusCode;
int numericStatusCode = (int)statusCode;
Run Code Online (Sandbox Code Playgroud)