title: How to Handle WebFaultException to return CustomException?
body: <p>I made my custom exception that will be thrown inside try-catch each time an error is occured:  </p>
  
  <pre><code>[Serializable]
  public class CustomException : Exception
  {
      public CustomException() { }
  
      public CustomException(string message)
          : base(message) { }
  
      public CustomException(string message, Exception innerException)
          : base(message, innerException) { }
  }  
  </code></pre>
  
  <p>I have two services, REST and SOAP. For SOAP services, I don't have any problem on throwing my custom exception.
  But in REST, I encountered a lot of difficulties.  </p>
  
  <p>Here is the method for throwing a WebFaultException:  </p>
  
  <pre><code>    public static WebFaultException RestGetFault(ServiceFaultTypes fault)
      {
          ServiceFault serviceFault = new ServiceFault();
          serviceFault.Code = (int)fault;
          serviceFault.Description = ConfigAndResourceComponent.GetResourceString(fault.ToString());
          FaultCode faultCode = new FaultCode(fault.ToString());
          FaultReasonText faultReasonText = new FaultReasonText(serviceFault.Description);
          FaultReason faultReason = new FaultReason(faultReasonText);
          WebFaultException&lt;ServiceFault&gt; webfaultException = new WebFaultException&lt;ServiceFault&gt;(serviceFault, HttpStatusCode.InternalServerError);
  
          throw webfaultException;
      }  
  </code></pre>
  
  <p>ServiceFault is a class where it has some properties which I use to put all information I need.</p>
  
  <p>I use this method to throw an exception inside REST service:  </p>
  
  <pre><code>    public static CustomException GetFault(ServiceFaultTypes fault)
      {
          string message = fault.ToString();
          CustomException cusExcp = new CustomException(message, new Exception(message));
          throw cusExcp;
      }  
  </code></pre>
  
  <p>A sample REST Service (log in method):  </p>
  
  <pre><code>    [WebInvoke(UriTemplate = "Login", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
      public Session Login(ClientCredentials client, LogCredentials loginfo)
      {
          try
          {
              // Login process
              return copied;
          }
          catch (LogicClass.CustomException ex)
          {
              LogicClass.RestGetFault(LogicClass.EnumComponent.GetServiceFaultTypes(ex.Message));
              throw ex;
          }
      }  
  </code></pre>
  
  <p>The MVC part:</p>
  
  <p>Controller:  </p>
  
  <pre><code>    [HttpPost]
      public ActionResult Login(LoginCredentials loginfo)
      {
          try
          {
              string param = "{\"client\":" + JSonHelper.Serialize&lt;ClientAuthentication&gt;(new ClientAuthentication() { SessionID = Singleton.ClientSessionID })
                             + ", \"loginfo\":" + JSonHelper.Serialize&lt;LoginCredentials&gt;(loginfo) + "}";
  
              string jsonresult = ServiceCaller.Invoke(Utility.ConstructRestURL("Authenticate/Login"), param, "POST", "application/json");
              UserSessionDTO response = JSonHelper.Deserialize&lt;UserSessionDTO&gt;(jsonresult);
  
          }
          catch (Exception ex)
          {
              return Json(new
              {
                  status = ex.Message,
                  url = string.Empty
              });
          }
  
          return Json(new
          {
              status = "AUTHENTICATED",
              url = string.IsNullOrWhiteSpace(loginfo.r) ? Url.Action("Index", "Home") : loginfo.r
          });
      }  
  </code></pre>
  
  <p>I use ServiceCaller.Invoke to call REST API and retrieve the response:
  ServiceCaller.cs  </p>
  
  <pre><code>public class ServiceCaller
  {
      public static string Invoke(string url, string parameters, string method, string contentType)
      {
          string results = string.Empty;
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
          request.Method = method;
          request.ContentType = contentType;
  
          if (!string.IsNullOrEmpty(parameters))
          {
              byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
              request.ContentLength = byteArray.Length;
              Stream dataStream = request.GetRequestStream();
              dataStream.Write(byteArray, 0, byteArray.Length);
              dataStream.Close();
          }
  
          try
          {
              HttpWebResponse response = (HttpWebResponse)request.GetResponse();
              if (HttpStatusCode.OK == response.StatusCode)
              {
                  Stream responseStream = response.GetResponseStream();
                  int length = (int)response.ContentLength;
  
                  const int bufSizeMax = 65536;
                  const int bufSizeMin = 8192;
                  int bufSize = bufSizeMin;
  
                  if (length &gt; bufSize) bufSize = length &gt; bufSizeMax ? bufSizeMax : length;
  
                  byte[] buf = new byte[bufSize];
                  StringBuilder sb = new StringBuilder(bufSize);
  
                  while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                      sb.Append(Encoding.UTF8.GetString(buf, 0, length));
  
                  results = sb.ToString();
              }
              else
              {
                  results = "Failed Response : " + response.StatusCode;
              }
          }
          catch (Exception exception)
          {
              throw exception;
          }
  
          return results;
      }
  }  
  </code></pre>
  
  <p>I am expecting the REST service to return this on client side:  </p>
  
  <p><img src="https://i.stack.imgur.com/aAphp.png" alt="enter image description here">  </p>
  
  <p>But in the end, it always return this:  </p>
  
  <p><img src="https://i.stack.imgur.com/V5Z8I.png" alt="enter image description here">  </p>
  
  <p>What should I do? Please help.</p>
  
  <p><strong>EDIT</strong>  </p>
  
  <p>Here is the sample response when calling the soap service:  </p>
  
  <pre><code>[FaultException: InvalidLogin]
     System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9441823  
  </code></pre>
  
  <p>Did you see the "InvalidLogin" ? That is what I want to see on the response from REST servivce.<br>
  Sample response from REST:  </p>
  
  <pre><code>[WebException: The remote server returned an error: (500) Internal Server Error.]
     System.Net.HttpWebRequest.GetResponse() +6115971  
  </code></pre>
  
  <p>I throw a <code>WebFaultException</code> but I receive a <code>WebException</code>.<br>
  If I won't be able to fetch the exact error message on REST, I will go for SOAP.<br>
  Thanks for the answers.</p>