Improve type conversion error message

This commit is contained in:
Sipke Schoorstra 2021-08-04 15:12:38 +02:00
parent 6965949976
commit 97b2cbfde4
2 changed files with 32 additions and 1 deletions

View file

@ -0,0 +1,22 @@
using System;
namespace Elsa.Exceptions
{
public class TypeConversionException : Exception
{
public object Value { get; }
public Type TargetType { get; }
public TypeConversionException(string message, object value, Type targetType) : base(message)
{
Value = value;
TargetType = targetType;
}
public TypeConversionException(string message, object value, Type targetType, Exception innerException) : base(message, innerException)
{
Value = value;
TargetType = targetType;
}
}
}

View file

@ -1,5 +1,6 @@
using System;
using System.ComponentModel;
using Elsa.Exceptions;
using Newtonsoft.Json.Linq;
using NodaTime;
using NodaTime.Text;
@ -53,8 +54,16 @@ namespace Elsa
if (underlyingSourceType != typeof(string))
return Enum.ToObject(underlyingTargetType, value);
}
try
{
return Convert.ChangeType(value, underlyingTargetType);
}
catch (InvalidCastException e)
{
throw new TypeConversionException($"Failed to convert an object of type {sourceType} to {underlyingTargetType}", value, underlyingTargetType, e);
}
return Convert.ChangeType(value, underlyingTargetType);
}
}
}