我正在使用RestSharp与REST服务器通信,并为该调用编写了一个小的包装函数。
private T Get<T>(string restAdress) where T : new()
{
try
{
// throw new Exception(); // This one is caught
IRestClient restClient = new RestClient(settings.Value.HostToConnect).UseSerializer(new JsonNetSerializer()); // (1)
RestRequest restRequest = new RestRequest(restAdress);
IRestResponse<T> result = restClient.Get<T>(restRequest); // (2)
return result.Data;
}
catch (Exception e) // debugger wont stop here
{
// debugger wont stop here too
// code within this block is not executed
}
return null; // (3)
}
因为我要使用我在自定义(反)序列化器(1)中提供的Newtonsoft属性。
public class JsonNetSerializer : IRestSerializer
{
public string Serialize(object obj) =>
JsonConvert.SerializeObject(obj);
public string Serialize(RestSharp.Parameter bodyParameter) =>
JsonConvert.SerializeObject(bodyParameter.Value);
public T Deserialize<T>(IRestResponse response) =>
JsonConvert.DeserializeObject<T>(response.Content); // (4)
public string[] SupportedContentTypes { get; } =
{
"application/json", "text/json", "text/x-json", "text/javascript", "*+json"
};
public string ContentType { get; set; } = "application/json";
public DataFormat DataFormat { get; } = DataFormat.Json;
}
在调用REST服务并尝试获得结果(2)时,如果反序列化失败(4),则会抛出Exception
。但是Exception
不会被try-catch
块捕获。我尝试调试,但在抛出调试器后继续执行第(3)行,catch
和带有catch的日志记录永远不会执行。调试器甚至不会停在catch (Exception e)
上,它会直接从(4)变为(3)。
(对不起,英语不好,窗口标题显示“ User-Unhandled Exception”)
有人可以向我解释这种行为吗?
答案 0 :(得分:2)
我正在维护RestSharp,所以希望我能回答这个问题。
RestSharp默认情况下不会进行反序列化。如果您看一下代码,反序列化就会在IRestResponse<T> Deserialize<T>(IRestRequest request, IRestResponse raw)
的私有RestClient
方法中进行。
当RestSharp无法反序列化响应时,它将创建一个错误响应。您将响应状态设置为Error
,并且将异常与进入响应ErrorException
的异常消息一起放入响应对象的ErrorMessage
属性中。>
如果将FailOnDeserialization
实例的RestClient
属性分配给true
,仍然可以告诉RestSharp进行反序列化。
答案 1 :(得分:1)
这里发生的事情是调试器的一个有趣的设置,另一个例子是closed bug report。当调试器到达该点时,将引发异常,该异常将中断,从而导致您遇到的行为。
如果在对话框中取消选中异常设置“此异常类型为用户未处理时中断”,则应该能够到达catch块,因为一旦抛出指定的异常,调试器将不再中断执行。
在您的情况下,您可以在“ Ausnahmeeinstellungen”下找到该选项。