Search code examples
c#jsonjson.netdeserializationjson-deserialization

Treating error on deserializing json


My problem basically is this: I have an output from an API that returns a json with one element called "error" with any message. When I'm trying to deserialize my object and the server returns me an error, I get this json rather than my json object (product, orders...).

This is the code where happens the error:

try
{
    using (var response = (HttpWebResponse)requisicao.GetResponse()) // **here happens the exception**
    {
        using (var stream = new StreamReader(response.GetResponseStream()))
            retorno = JsonConvert.DeserializeObject<TModelo>(stream.ReadToEnd());
    }
}

So... I'd like to get this message error but I can't handler (deserialize) it because it gets me an exception. If I could deserialize the object I could get the error message because the entity that represents my object inherits the error object (this one bellow)

public class Erro
{
    [JsonProperty("error")]
    string MensagemErro { get; set; }
}

Thanks in advance.


Solution

  • If you encountered with error while getting response;

    (HttpWebResponse)requisicao.GetResponse()
    

    It means that the server didn't return proper message to you. So, there is no response message to deserialize and the only option is handling the error within catch block.

    It looks something like;

    try
    {
        using (var response = (HttpWebResponse)requisicao.GetResponse()) // **here happens the exception**
        {
            using (var stream = new StreamReader(response.GetResponseStream()))
                retorno = JsonConvert.DeserializeObject<TModelo>(stream.ReadToEnd());
        }
    }
    catch (WebException e)
    {
        WebResponse response = e.Response;
        using (StreamReader reader =
            new StreamReader(response.GetResponseStream()))
        {
            string text = reader.ReadToEnd();//Content of error message
        }
    }