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);
}