Hope the following sample code helps you...

-Sundar

import javax.script.*;
import jdk.nashorn.api.scripting.*;

public class Main {
  private static JSObject errorCtr;

  public static void main(String[] args) throws Exception {
     ScriptEngine e = new ScriptEngineManager().getEngineByName("nashorn");
// save JS Error constructor which is used later to construct Error object
     errorCtr = (JSObject)e.eval("Error");
     e.put("func", new MyFunc());
     e.eval("try { func() } catch(e) { print(e); print(e.stack); } ");
  }

  public static class MyFunc extends AbstractJSObject {
      public boolean isFunction() { return true; }

      public Object call(Object self, Object... args) {
          // this is like "var e = new Error('myErrorMsg')" in JS code
          JSObject error = (JSObject)errorCtr.newObject("myErrorMsg");
          // equivalent to "throw e;"
          throw (RuntimeException)error.getMember("nashornException");
      }
  }
}


On 31/01/17, 10:04 PM, Attila Sari wrote:
Hi all,

Is it possible to throw ecmascript error from JSObject methods? (that can
be catched later in the script, and will be enriched with filename and line
number)

Thanks,
Attila Sari

Reply via email to