Преглед изворни кода

Added support for catching exceptions from CLR code (#326)

Massimiliano Gentile пре 8 година
родитељ
комит
c521b590fa
2 измењених фајлова са 32 додато и 2 уклоњено
  1. 22 0
      Jint.Tests/Runtime/InteropTests.cs
  2. 10 2
      Jint/Runtime/Interop/DelegateWrapper.cs

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

@@ -1438,5 +1438,27 @@ namespace Jint.Tests.Runtime
                 assert(new String(zero) == zero.toString());
             ");
         }
+
+        [Fact]
+        public void ShouldCatchClrExceptions()
+        {
+            string exceptionMessage = "myExceptionMessage";
+            _engine.SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }));
+                        
+            RunTest(@"
+                function throwException(){
+                try {
+                    throwMyException();
+                    return '';
+                } 
+                catch(e) {
+                    return e.message;
+                }
+            }
+            ");
+            var result = _engine.Invoke("throwException");
+            Assert.Equal(result.AsString(), exceptionMessage);
+        }
+
     }
 }

+ 10 - 2
Jint/Runtime/Interop/DelegateWrapper.cs

@@ -4,6 +4,7 @@ using System.Linq;
 using System.Reflection;
 using Jint.Native;
 using Jint.Native.Function;
+using System.Reflection;
 
 namespace Jint.Runtime.Interop
 {
@@ -92,8 +93,15 @@ namespace Jint.Runtime.Interop
                 }
                 parameters[paramsArgumentIndex] = paramsParameter;
             }
-
-            return JsValue.FromObject(Engine, _d.DynamicInvoke(parameters));
+            try
+            {
+                return JsValue.FromObject(Engine, _d.DynamicInvoke(parameters));
+            }
+            catch (TargetInvocationException exception)
+            {
+                var meaningfulException = exception.InnerException ?? exception;
+                throw new JavaScriptException(Engine.Error, meaningfulException.Message);
+            }
         }
     }
 }