From 87fcb77e8bc3a6b208b9d8e54dab8ca735e0cdea Mon Sep 17 00:00:00 2001 From: Drew Shafer Date: Fri, 9 Jan 2015 15:47:38 -0600 Subject: [PATCH] Fix for NullReferenceException thrown when server is unavailable --- ToopherDotNet/ToopherDotNet.cs | 46 ++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/ToopherDotNet/ToopherDotNet.cs b/ToopherDotNet/ToopherDotNet.cs index 87c2daa..4fcccd3 100644 --- a/ToopherDotNet/ToopherDotNet.cs +++ b/ToopherDotNet/ToopherDotNet.cs @@ -252,31 +252,35 @@ private object request (string method, string endpoint, NameValueCollection para response = wClient.DownloadString (client.RequestUrl); } } catch (WebException wex) { - IHttpWebResponse httpResp = HttpWebResponseWrapper.create(wex.Response); - string error_message; - using (Stream stream = httpResp.GetResponseStream ()) { - StreamReader reader = new StreamReader (stream, Encoding.UTF8); - error_message = reader.ReadToEnd (); - } + if (wex.Response != null) { + IHttpWebResponse httpResp = HttpWebResponseWrapper.create(wex.Response); + string error_message; + using (Stream stream = httpResp.GetResponseStream ()) { + StreamReader reader = new StreamReader (stream, Encoding.UTF8); + error_message = reader.ReadToEnd (); + } - String statusLine = httpResp.StatusCode.ToString () + " : " + httpResp.StatusDescription; + String statusLine = httpResp.StatusCode.ToString () + " : " + httpResp.StatusDescription; + + if (String.IsNullOrEmpty (error_message)) { + throw new RequestError (statusLine); + } else { + + try { + // Attempt to parse JSON response + var json = (JsonObject)SimpleJson.SimpleJson.DeserializeObject (error_message); + parseRequestError (json); + } catch (RequestError e) { + throw e; + } catch (Exception) { + throw new RequestError (statusLine + " : " + error_message); + } + } - if (String.IsNullOrEmpty (error_message)) { - throw new RequestError (statusLine); + throw new RequestError (error_message, wex); } else { - - try { - // Attempt to parse JSON response - var json = (JsonObject)SimpleJson.SimpleJson.DeserializeObject (error_message); - parseRequestError (json); - } catch (RequestError e) { - throw e; - } catch (Exception) { - throw new RequestError (statusLine + " : " + error_message); - } + throw new RequestError ("Unable to contact server", wex); } - - throw new RequestError (error_message, wex); } try {