0

I have a method where I call DownloadData on a WebClient. This method throws an exception since the URL returns 404. This is all expected by specifications since the resource does not exist.

Web client will throw a WebException and I have to read body from respose since it contains JSON object with detailed error. After that I have to throw a WebException again since the layer up still expects the WebException. At the moment I am trying to construct a WebException with details from the current one as follows:

catch(WebException ex)
{
   var response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();   
   dynamic error = JsonConvert.DeserializeObject(response);
   throw new WebException(error.message, null, ex.Status, ex.Response);
}

The problem is I get an exception while constructing WebException. This is the message!

The best overloaded method match for 'System.Net.WebException.WebException(string, System.Net.WebExceptionStatus, System.Net.WebExceptionInternalStatus, System.Exception)' has some invalid arguments

It is like this constructor does not exist! Check the constructor in exception and check the constructor in catch block.

As you can see I am using a valid constructor. Check here.

What is happening here?

Stoyan Dimov
  • 5,250
  • 2
  • 28
  • 44
Robert
  • 2,407
  • 1
  • 24
  • 35

1 Answers1

1

The problem is, that you need to cast error.message as string. It would be even better if you would handle that string differently so you can verify if that error.message exists.

catch(WebException ex)
{
    var response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();   
    dynamic error = JsonConvert.DeserializeObject(response);
    throw new WebException((string)error.message, null, ex.Status, ex.Response);
}
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
MaticDiba
  • 895
  • 1
  • 11
  • 19
  • As I said, try putting addtional check for error object, becaus it may not contain message property and then you will have another exception :) – MaticDiba Feb 15 '17 at 08:58