I have the exact same problem as in Recreate an exception that is serialized in a JSON response, but I have managed to instantiate the correct type of exception:
public class ServiceExceptionData
{
public string Type { get; set; }
public string Message { get; set; }
public string ErrorCode { get; set; }
public string StackTrace { get; set; }
}
...
private static void handleServiceException(ServiceExceptionData serviceException)
{
// get exception type
Type t = Type.GetType(serviceException.Type);
// create exception instance
var exceptionInstance = Activator.CreateInstance(t);
// set exception read-only properties: Message, StackTrace
???
I tried a lot of things to set those properties, here are some of them:
- Can I change a private readonly field in C# using reflection?
- Changing read only properties with reflection
- Set object property using reflection
- Is it possible to get a property's private setter through reflection?
- Is any simple way to create method and set its body dynamically in C#?
but it doesn't work.
The Exception's properties are defined as:
public virtual string Message { get; }
public virtual string StackTrace { get; }
So is there any way to set them once I have the exception instance (e.g. by getting the property's field and using SetValueDirect
) or should I give up and create a derived class and override the properties to give them public setters?