I'm using RestSharp to communicate with a REST-Server and wrote a small wrapper function for the call
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)
}
Since I want to use the Newtonsoft-Attributes I give in a custom (de)serializer (1).
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;
}
When calling the REST service and trying to get the result (2) an Exception
is thrown if the deserialization fails (4). But the Exception
is not caught by the try-catch
block. I tried to debug but after throwing the debugger goes on in line (3), the catch
and the logging withing the catch is never executed. The debugger won't even stop at the catch (Exception e)
it goes straight from (4) to (3).
(Sorry for not english, the title of the window says "Exception User-Unhandled")
Can anyone explain this behaviour to me?
Whats happening here is an interesting setting of the debugger, another example would be this closed bug report. When the debugger reaches the point the exception is thrown it will break, causing the behaviour you experienced.
If you uncheck the exception setting "Break when this exception type is user-unhandled" in the dialog, you should be able to reach your catch block, as the debugger no longer breaks the execution as soon as the specified exception is thrown.
In your case you find that option under "Ausnahmeeinstellungen".