0

我想捕捉从 javascript 抛出的 clr 异常。以下是我尝试过的事情。

var registerScript = new Engine(c => c.AllowClr(typeof(Manager).Assembly ).CatchClrExceptions(ExceptionHandler(new Exception("Exception")) )).Execute("javascriptCode").GetValue("JavascriptFunction");

public static Predicate<Exception> ExceptionHandler(Exception ex)
{
      throw new Exception(ex.Message);
}

但我想要我喜欢这个,

 var registerScript = new Engine(c => c.AllowClr(typeof(Manager).Assembly ).CatchClrExceptions(e=>ExceptionHandler(new Exception(e.Message)) )).Execute("javascriptCode").GetValue("JavascriptFunction");

即,我想从 javascript 中捕获异常并获取该异常消息。

请帮助解决这个问题。

4

1 回答 1

0

CatchClrExceptions允许您捕获源自程序集的异常,并指示 Jint 引擎应将异常传递给 JS 代码,或者将其作为 .NET 异常抛出。

namespace ConsoleApp5
{
    public class Program
    {
        public static void Helper(string msg)
        {
            throw new Exception(msg);
        }
        static void Main(string[] args)
        {
            var registerScript = new Engine(c => c
                .AllowClr(typeof(Program).Assembly)
                // Allow exceptions from this assembly to surface as JS exceptions only if the message is foo
                .CatchClrExceptions(ex => ex.Message == "foo")
            )
            .Execute(@"function throwException(){ 
                    try { 
                        var ConsoleApp5 = importNamespace('ConsoleApp5');
                        ConsoleApp5.Program.Helper('foo'); 
                        // ConsoleApp5.Program.Helper('goo'); // This will fail when calling execute becase the predicate returns false 
                        return ''; 
                    }  
                    catch(e) { 
                        return e; 
                    } 
            };
            var f = throwException();")
            .GetValue("f");
        }
    }
}

Predicate传递给应该CatchClrExceptions返回真/假。它将接收抛出的 CLR 异常。

Jint 运行时似乎无法通知已处理的异常。要捕获解析器异常(即无效的 JS 代码),您可以Execute用常规包围 ,try..catch(ParserException ex) { .. }这将捕获任何解析异常。对于运行时异常,您还可以捕获JavaScriptException将在执行时抛出未处理的异常。

var engine = new Engine(c => c
    .DebugMode()
    .AllowClr(typeof(Program).Assembly)
);

engine.Step += Engine_Step;

try
{
    var r = engine
    .Execute(@"function throwException(){ 
        // undefined.test(); // This will cause a runtime exception
        // fun ction test () { } // This will cause a parser exception
        try { 
            throw 'Handled exception'; // No notification on this exception it is handled in JS
            return ''; 
        }  
        catch(e) { 
            return e; 
        } 
};
var f = throwException();")
    .GetValue("f");
}
catch (ParserException pEx)
{
    Console.WriteLine("Parser Exception " + pEx.Message);
}
catch (JavaScriptException rEx)
{
    Console.WriteLine("Runtime Exception " + rEx.Message);
}
于 2018-01-22T05:06:29.283 回答