views:

294

answers:

1

I'm working on a client for a webservice that returns standard Status Codes (404, 200 etc) as well a custom json message.

I haven't been able to find a property of the WebException that contains the custom message.

Any ideas on how to get a hold of the message?

A: 

Simple solution:

The WebException has the actual WebResponse available in the Response property. From here it is simply a matter of handling the response as per normal:

    private static JsonParseException ProcessException(WebException webEx)
    {
        var stream = webEx.Response.GetResponseStream();
        using (var memory = new MemoryStream())
        {
            var buffer = new byte[4096];
            var read = 0;
            do
            {
                read = stream.Read(buffer, 0, buffer.Length);
                memory.Write(buffer, 0, read);

            } while (read > 0);

            memory.Position = 0;
            int pageSize = (int)memory.Length;
            byte[] bytes = new byte[pageSize];
            memory.Read(bytes, 0, pageSize);
            memory.Seek(0, SeekOrigin.Begin);
            string data = new StreamReader(memory).ReadToEnd();

            memory.Close();
            DefaultMeta meta = JsonConvert.DeserializeObject<DefaultMeta>(data);
            return new JsonParseException(meta.Meta, meta.Meta.Error, webEx);
        }
    }

I'm using the NewtonSoft Json library to deserialise the Json response

Harry