I'm looking essentially for the same thing asked here: Any way to access response body using WebClient when the server returns an error?
But no answers have been provided so far.
The server returns a "400 bad request" status, but with a detailed error explanation as response body.
Any ideas on accessing that data with .NET WebClient? It just throws an exception when server returns an error status code.
While Initialising WebClient As mentioned in the code block, whenever a 5XX/4XX Error occurs, we can throw a user defined exception, and then execute error handling logic based on those user defined exceptions. Once this error Handler is defined, we can add it in the WebClient Initialisation.
Be aware that [unlike with HttpClient] 4xx and 5xx responses result in a WebException being thrown at the "response = base. GetWebResponse(request);" line. You can pull the status and response from the exception (if they exist). Yes.
You would just use bodyToMono which would return a Mono object. WebClient webClient = WebClient. create(); String responseJson = webClient. get() .
As you can see, ServiceException includes both a message and a status code. That's the exception that gets included in the Mono publisher. It's also the exception that gets thrown when the WebClient encounters a 405 HTTP status code.
You cant get it from the webclient however on your WebException you can access the Response Object cast that into a HttpWebResponse object and you will be able to access the entire response object.
Please see the WebException class definition for more information.
Below is an example from MSDN (added reading the content of the web response for clarity)
using System; using System.IO; using System.Net; public class Program { public static void Main() { try { // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name. HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL"); // Get the associated response for the above request. HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse(); myHttpWebResponse.Close(); } catch(WebException e) { Console.WriteLine("This program is expected to throw WebException on successful run."+ "\n\nException Message :" + e.Message); if(e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream())) { Console.WriteLine("Content: {0}", r.ReadToEnd()); } } } catch(Exception e) { Console.WriteLine(e.Message); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With