Selaa lähdekoodia

Check ExceptionHandler if type conversion fails (#988)

Marko Lahma 3 vuotta sitten
vanhempi
commit
6082013b16

+ 8 - 0
Jint.Tests/Runtime/InteropTests.cs

@@ -2865,5 +2865,13 @@ namespace Jint.Tests.Runtime
             Assert.Equal((int) CustomNamedEnum.HeadersReceived, engine.Evaluate("o.jsEnumProperty").AsNumber());
         }
 
+        [Fact]
+        public void ShouldBeAbleToHandleInvalidClrConversionViaCatchClrExceptions()
+        {
+            var engine = new Engine(cfg => cfg.CatchClrExceptions());
+            engine.SetValue("a", new Person());
+            var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("a.age = \"It won't work, but it's normal\""));
+            Assert.Equal("Input string was not in a correct format.", ex.Message);
+        }
     }
 }

+ 1 - 1
Jint/Runtime/ExceptionHelper.cs

@@ -146,7 +146,7 @@ namespace Jint.Runtime
         }
 
         [DoesNotReturn]
-        private static void ThrowError(Engine engine, string message)
+        internal static void ThrowError(Engine engine, string message)
         {
             throw new JavaScriptException(engine.Realm.Intrinsics.Error, message);
         }

+ 14 - 1
Jint/Runtime/Interop/DefaultTypeConverter.cs

@@ -232,7 +232,20 @@ namespace Jint.Runtime.Interop
                 }
             }
 
-            return System.Convert.ChangeType(value, type, formatProvider);
+            try
+            {
+                return System.Convert.ChangeType(value, type, formatProvider);
+            }
+            catch (Exception e)
+            {
+                if (!_engine.Options.Interop.ExceptionHandler(e))
+                {
+                    throw;
+                }
+
+                ExceptionHelper.ThrowError(_engine, e.Message);
+                return null;
+            }
         }
 
         public virtual bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)