jeudi 4 janvier 2018

Retrieve Object From String C#

I have the below mapper json file, which tells me for a given exception, which error handling policy I want to use.

{
  "ExceptionMappers": [
   {
     "ExceptionName": "TimeoutException",
     "ExceptionType": "Transient",
  "Policy": "WaitAndRetry",
  "WaitType": "Linear"
},
{
  "ExceptionName": "DivideByZeroException",
  "ExceptionType": "Permanent",
  "Policy": "CircuitBreaker"
},
{
  "ExceptionName": "StackOverflowException",
  "ExceptionType": "LogOnly",
  "Policy": "WaitAndRetry",
  "WaitType": "Linear"
}
]
 }

Then using the below code I am trying to get the type of exception and apply a policy using which the action can be called. But here I am stuck, how to get the exception type from a string name.

   public void Execute(Action action, string exceptionName)
    {
        var filePath = @"appsetting.json";
        var exceptionMapperJson = System.IO.File.ReadAllText(filePath);
        var rootNode = JsonConvert.DeserializeObject<RootObject>(exceptionMapperJson);

        var exceptionNode = rootNode.ExceptionMappers.FirstOrDefault(e => e.ExceptionName.Equals(exceptionName));
        var exceptionObject = Type.GetType(exceptionName);

        if (exceptionNode != null)
        {
            // Here I need the exception from the string value
            Policy.Handle<TimeoutException>().Retry().Execute(action);
        }
        else
        {
            // No Policy applied
            Policy.NoOp().Execute(action);
        }

    }





Aucun commentaire:

Enregistrer un commentaire