Getting JS exception

Mar 11, 2014 at 1:33 PM
Hi there,

I'm back with more exception-related questions! :)
Now I'm trying to handle (or at least, correctly log) an unhandled exception thrown from JS.

Something like this:
engine.Execute("throw 'hello'");
will throw a ScriptEngineException with its Message set to 'hello'.

But when the JS throws an object, like:
engine.Execute("throw { field: 'hello' }");
it looks like there is no way to retrieve the object from the ScriptEngineException, whose Message only says "[object Object]".

I get pretty much the same results when throwing a CLR object from JS, with the exception's Message getting "[object HostObject]".

So is there any other way to catch in .NET objects thrown from JS?

Thanks!
Coordinator
Mar 11, 2014 at 3:51 PM
Hello!

This question is similar to your earlier one about catching .NET exceptions in JavaScript, and our answer is similar as well - consider catching the exception in JavaScript and allowing .NET code to inspect it. For example:
engine.Execute(@"
    function tryCatch(func) {
        try {
            return { isSuccess: true, returnValue: func() };
        }
        catch (exception) {
            return { isSuccess: false, exception: exception };
        }
    }
");
and then:
dynamic result = engine.Evaluate(@"tryCatch(function() {
    throw { foo: 123, bar: 456 };
})");

if (!result.isSuccess)
{
    Console.WriteLine(result.exception.foo);
    Console.WriteLine(result.exception.bar);
}
else
{
    Console.WriteLine(result.returnValue);
}
As you can see, the host and the script engine can work together!

Good luck!
Mar 12, 2014 at 2:55 AM
Hi,

Well, by reading your answer, the workaround looks obvious! :)
Thanks for the help.

Is there any plan to have more seamless exception handling between .NET and JS, even for V8 only? That would be definitely nice!

Cheers
Coordinator
Mar 14, 2014 at 2:49 AM
Hello!

Is there any plan to have more seamless exception handling between .NET and JS, even for V8 only?

Currently there's no plan beyond adding a script-callable tryCatch() function on the host side. Generally we favor keeping the engine APIs uniform, but we agree that this may be worth doing anyway, so we've put it on our long-term to-do list.

Thanks for your input!