Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Handling CLR exceptions in JS

0
0
Hi Thomas,

ClearScript doesn't expose .NET exceptions through the script language's native exception handling mechanism. V8 actually might make this possible, but JScript and VBScript definitely do not.

Instead, we recommend that you expose a function that runs script code inside a .NET try/catch block and returns any caught exception to the script. For example:
engine.Script.tryCatch = new Func<dynamic, object>(func => {
    try {
        returnnew { returnValue = func() };
    }
    catch (Exception exception) {
        returnnew { exception = exception.GetBaseException() };
    }
});
Here's an example of how you'd use such a function:
engine.AddHostType("File", typeof(File));
engine.AddHostType("Console", typeof(Console));
engine.Execute(@"
    result = tryCatch(function () {
        return File.ReadAllText('SomeFileName.txt');
    });
    if (result.exception)
        Console.WriteLine(result.exception);
    else
        Console.WriteLine(result.returnValue);
");
Hopefully this solution, or something similar, is practical in your scenario.

Cheers!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images