我正在和restsharp一起做一个项目。随着时间的推移,我发现了REST响应类可以抛出的几个例外,其中大部分是我必须处理的,所以我的应用程序不会崩溃。如何知道所有可能的异常并单独处理它们。
最佳答案
限制和错误
这是RestSharp's wiki
错误处理注意事项
**如果存在网络传输错误(网络关闭、DNS查找失败等),resresponse.status将设置为responseStatus.error,**否则将为responseStatus.completed。如果api返回404,responseStatus仍将完成。如果您需要访问返回的http状态代码,您可以在resresponse.status code找到它。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;
}
因此,你知道你可以期待标准.NET异常。recommended usage建议只检查代码示例中是否存在类似于
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;
}
如果要对某类异常执行特定操作,只需使用如下行执行类型比较。
if (response.ErrorException.GetType() == typeof(NullReferenceException))
{
//handle error
}
如何知道所有可能的异常并单独处理它们。
老实说,我建议不要单独捕捉所有的异常,我会发现这个特殊的要求是有问题的。你确定他们不只是想让你catch and handle exceptions gracefully?
如果您绝对需要单独处理每个可能的情况,那么我将记录测试中出现的异常并对照这些异常进行检查。如果你试着抓住每件事,你可能会有超过一百个不同的例外。这就是碱基Exception class的作用。
exception类是用来处理从exception继承的所有内容的catch all。一般的想法是,你要特别注意,你可以做一些事情,比如通知用户互联网不可用或者远程服务器宕机,让异常类处理任何其他边缘情况。msdn link
关于c# - 如何使用RestSharp捕获异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31222768/