如何使用RestSharp捕获异常

oke*_*ley 13 c# exception restsharp

我正在与RestSharp合作开展一个项目.随着时间的推移,我发现了RestResponse类可以抛出的几个异常,其中大部分是我必须处理的,所以我的应用程序不会崩溃.我如何知道所有可能的异常并单独处理它们.

Ter*_*nce 28

RestResponses和错误

这是来自RestSharp维基的文档

注意错误处理

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

这就是说,检查状态的推荐方法RestResponse是看RestResponse.Status

内部Execute调用的源本身如下所示.

private IRestResponse Execute(IRestRequest request, string httpMethod,Func<IHttp, string, HttpResponse> getResponse)
{
    AuthenticateIfNeeded(this, request);
    IRestResponse response = new RestResponse();
    try
    {
        var http = HttpFactory.Create();

        ConfigureHttp(request, http);

        response = ConvertToRestResponse(request, getResponse(http, httpMethod));
        response.Request = request;
        response.Request.IncreaseNumAttempts();

    }
    catch (Exception ex)
    {
        response.ResponseStatus = ResponseStatus.Error;
        response.ErrorMessage = ex.Message;
        response.ErrorException = ex;
    }

    return response;
}
Run Code Online (Sandbox Code Playgroud)

因此,您知道可以期待标准的.net异常.在推荐的使用提出了一个的存在只是检查ErrorException等中的代码示例.

//Snippet of code example in above link
var response = client.Execute<T>(request);

if (response.ErrorException != null)
{
    const string message = "Error retrieving response.  Check inner details for more info.";
    var twilioException = new ApplicationException(message, response.ErrorException);
    throw twilioException;
}
Run Code Online (Sandbox Code Playgroud)

如果要对特定类型的异常执行特定操作,只需使用如下所示的行执行类型比较.

if (response.ErrorException.GetType() == typeof(NullReferenceException))
{
  //handle error
}
Run Code Online (Sandbox Code Playgroud)

我如何知道所有可能的异常并单独处理它们.

老实说,我建议不要单独捕获所有异常,我会发现这个特殊要求有问题.你确定他们不只是希望你优雅地捕捉和处理异常吗?

如果您绝对需要单独处理每个可能的情况,那么我将记录测试中出现的异常并检查这些异常情况.如果你试图抓住一切,你可能有超过一百个不同的例外.这就是基础Exception类的用途.

异常类是处理从Exception继承的任何东西的catch-all.一般的想法是,您要特别注意您可以实际执行某些操作的异常,例如通知用户Internet不可用或远程服务器已关闭,并让异常类处理任何其他边缘情况.msdn链接