-1

I am working on WCF REST project. On WCF/server side whenever an exception happens in my catch block I do below and send exception as json string in my response to client.

public MyResponse GetData(MyRequest request)
{
   MyResponse response = new MyResponse();
   try
   {
       // do something
   }
   catch(Exception ex)
   { 
      response.success = false;
      response.ExceptionJSONString = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
   }
   return response;
}

Please see below for my client side

enter image description here

My question is there a way to deserialize Exception object. I feel you cannot do since Exception class inherits ISerializable. But just want to ask around and see anyone did it.

UPDATE : I was able to get the exact exception object from client to server like below

Create below DataContract class

[DataContract]
public class MyExceptionJson
{
   [DataMember]
   public string JsonData { get; set; }

   [DataMember]
   public string AssemblyName { get; set; }

   [DataMember]
   public string TypeName { get; set; }

   public MyExceptionJson()
   {
      JsonData = string.Empty;
      AssemblyName = string.Empty;
      TypeName = string.Empty;
   }

   public MyExceptionJson(Exception exception)
   {
      JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(exception);
      Type type = exception.GetType();
      AssemblyName = type.Assembly.GetName().Name;
      TypeName = type.FullName;
   }

    public Exception ToException()
    {
       if (string.IsNullOrEmpty(JsonData) == true ||
           string.IsNullOrEmpty(AssemblyName) == true ||
           string.IsNullOrEmpty(TypeName) == true)
         {
            return new Exception();
         }

       Type type = null;
      foreach (Assembly item in System.AppDomain.CurrentDomain.GetAssemblies())
      {
         AssemblyName assemblyName = item.GetName();
          if (assemblyName != null &&
              string.IsNullOrEmpty(assemblyName.Name) == false &&
              assemblyName.Name == AssemblyName)
            {
               type = item.GetType(TypeName);
               if (type != null)
                   break;
             }
        }
        //fail safe code
        if (type == null)
        {
           type = typeof(Exception);
        }
     object returnException = Newtonsoft.Json.JsonConvert.DeserializeObject(JsonData, type);
     return returnException as Exception;
     }
}

Added property of this class type in my response class like below

[DataContract]
public class MyResponse 
{
   [DataMember]
   public bool Success { get; set; }

   [DataMember]
   public MyExceptionJson ExceptionDataAsJson { get; set; }
}

Server: When exception happens

  MyResponse response = new MyResponse()
  {
     Success = false,
     ExceptionDataAsJson = null
  };

  try 
  {
     //code 
  }
  catch(Exception ex)
  {
      response.ExceptionDataAsJson = new MyExceptionJson(ex);
  }
  return response;

Client: When you get response back

 if (response != null && response.Success == false)
 {
  Exception ex = null;
  //something went wrong                    
  if (response.ExceptionDataAsJson != null)
  {
    ex = response.ExceptionDataAsJson.ToException();                        
  }
 }
Ziggler
  • 3,361
  • 3
  • 43
  • 61

1 Answers1

2

You can just use Newtonsoft.Json.JsonConvert.DeserializeObject<T> So change your code to this:

Exception ex = Newtonsoft.Json.JsonConvert.DeserializeObject<Exception>(upResponse.ExceptionJSONString);
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
  • Ryan....We are trying to improve this solution in our project.. instead of always deserializing to Exception we want to deserialize to exact exception type that we receive from WCF/server side... I am looking into it... any suggestions... – Ziggler Jan 23 '19 at 18:16
  • @Ziggler All exceptions inherit from `Exception`, so I would think you could cast it to the specific `Exception` type. – Ryan Wilson Jan 23 '19 at 18:18
  • But from my WCF/server side I am getting exception in json string... I feel I need to somehow pass exception type to client and then deserialize to that type.. but this way needs checking each exception type from server – Ziggler Jan 23 '19 at 18:19
  • @Ziggler Even if you add the exact type of exception to your json, you are going to have to do an `if-else if`, or `switch` to decide what type to deserialize to, so either way you are going to have to do a type check when receiving the response. – Ryan Wilson Jan 23 '19 at 18:20
  • Ryan.. yes I also agree I need to use conditional operators.. that's what I am trying to avoid... – Ziggler Jan 23 '19 at 18:24
  • @ziggler I don't know any way around that if your goal is to deserialize to specific exception types. You could create your own custom `Exception` class which inherits `Exception` and give it a property of `ExceptionType` which you could `deserialize` from your `json` and pass that custom exception type back from your WCF. You'd still need some conditionals based on the exception type property. – Ryan Wilson Jan 23 '19 at 18:25
  • @Ziggler Please see my edited comment, I added a possible solution, but you'd still need to use some kind of business logic (conditional) by looking at the Property. – Ryan Wilson Jan 23 '19 at 18:28
  • @Ziggler You may also want to look at this other Stack Overflow post, it deals with what I think you are trying to do, `dynamic casting` (https://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast). I'm sorry but I don't have any other ideas for you at this time. You may want to make another post asking about this and see if other developers can help. – Ryan Wilson Jan 23 '19 at 18:31
  • Seeing it...Thanks – Ziggler Jan 23 '19 at 18:32
  • Ryan.. I am passing exceptiontype to client and doing this.. Type exceptionType = Type.GetType(exType);.. object ex = Newtonsoft.Json.JsonConvert.DeserializeObject(exString, type);... I am stuck at casting object ex …. looking in more... – Ziggler Jan 23 '19 at 22:53
  • @Ziggler I don't think there is any way to avoid using conditionals for your casting, this Stack Overflow post I think addresses what you are trying to achieve using `Type` (https://stackoverflow.com/questions/4800446/declare-a-variable-using-a-type-variable) – Ryan Wilson Jan 24 '19 at 00:15
  • Ryan.. I was able get exact exception object from server to client. I updated my question with solution. Please review... – Ziggler Feb 05 '19 at 22:47