graal js interpreter can't catch custom new Error

377 Views Asked by At
try {
  if (typeof hostObj['propertyItDoesntHave'] === "undefined") {
    throw new Error('first');
  }
} catch (e) {
  throw new Error('second');
}

For me, this is always crashing with:

org.graalvm.polyglot.PolyglotException: Error: first
    at <js>.:anonymous(Unnamed:21) ~[?:?]
    at <js>.:=>(Unnamed:21) ~[?:?]
    at <js>.:=>(Unnamed:21) ~[?:?]

i.e. the catch block is never reached, the first error seems to be stopping the program.

How can I get the GraalVM JavaScript interpreter to catch nested errors like this?

1

There are 1 best solutions below

0
On

I think it should work out of the box. If it doesn't it is probably a bug. Can you please submit an issue to https://github.com/oracle/graaljs.

It does work for me in the simplest test, I'm trying on the latest release 21.1 both node and js.

which node
~/21.1/graalvm-ce-java11-21.1.0/bin/node
[opc@ol8-demo 21.1]$ node
Welcome to Node.js v14.16.1.
Type ".help" for more information.
> try {
...   if (typeof hostObj['propertyItDoesntHave'] === "undefined") {
.....     throw new Error('first');
.....   }
... } catch (e) {
...   throw new Error('second');
... }
Uncaught Error: second
>
>
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
>
[opc@ol8-demo 21.1]$ js
> try {
>   if (typeof hostObj['propertyItDoesntHave'] === "undefined") {
>     throw new Error('first');
>   }
> } catch (e) {
>   throw new Error('second');
> }
>
Error: second
    at <js> :program(<shell>:1:6:126-144)
>

Also when embedding JS in a Java application:

import org.graalvm.polyglot.*;
import org.graalvm.polyglot.Context.Builder;
import org.graalvm.polyglot.proxy.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        try (Context context = Context.newBuilder()
            .allowAllAccess(true)
            .build()) {
            
            context.eval("js",
                "{ " +
                "try {" +
                "  if (typeof hostObj['propertyItDoesntHave'] === \"undefined\") {" +
                "    throw new Error('first');" +
                "  }" +
                "} catch (e) {" +
                "  throw new Error('second'); " +
                " } " +
                "}");

        }
    }
}

I do get the second:

javac Main.java && java Main
Exception in thread "main" Error: second
    at <js> :program(Unnamed:1:123-141)
    at org.graalvm.sdk/org.graalvm.polyglot.Context.eval(Context.java:379)
    at Main.main(Main.java:12)