我想捕捉从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捕获异常并获取异常消息。
请帮我一下。
发布于 2018-01-22 05:06:29
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");
}
}
}传递给CatchClrExceptions的CatchClrExceptions应该返回true/false。它将接收引发的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);
}https://stackoverflow.com/questions/48374822
复制相似问题