Is it possible to pass information from Rhino to Java through an exception?

Using the JDK 6 mechanism ScriptEngine, everything that goes wrong during "eval" or "invokeMethod" or something else leads to a return ScriptExceptionto the Java calling environment. As far as I could tell from experimenting and reading the source code, the best I can do to get the information back from Javascript when my Javascript code wants to throw an exception is to throw a line. This string is displayed in the return value "getMessage" from the object ScriptException. Not really.

It seems to be nice to be able to:

 if (somethingWrong) {
   throw { error: Errors.INVALID_SOMETHING, context: whatever() };
 }

from Javascript, and then Java code may somehow get to this object. However, I fear that given the current implementation of the Rhino shell, ScriptEnginethis is simply not possible. However, if someone knows a trick that really works, I would love to see it.

+3
source share
3 answers

Rhino has poor support for Exceptions, they are not usable or useful, as in other scripts such as Groovy or JRuby.

To help you debug problems, I think you can use this trick. Rhino adds a non-standard property to the Error object, which you can access to print some error information.

try {
   someCode()
}
catch(e) { 
     if(e.rhinoException != null) 
     { 
         e.rhinoException.printStackTrace();
     } 
}

Bindings, , - ?

, . , , JavaScriptException, , .

package test;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import sun.org.mozilla.javascript.*;

public class Main {
    private static ScriptEngineManager mgr = new ScriptEngineManager();
    private static ScriptEngine engine = mgr.getEngineByName("JavaScript");

    public static void main(String... args) {
        System.out.println("START");
        try {
            engine.eval("throw { error: \"cheese\", context: \"payload\" };");
        } catch (ScriptException e) {
            JavaScriptException jse = (JavaScriptException)e.getCause();
            Object obj = jse.getValue();
            ScriptableObject so = (ScriptableObject)obj;
            System.out.println(so.get("error", so));
            System.out.println(so.get("context", so));
        }
        System.out.println("END");
    }
}
+2

JSON Java.

0

FWIW, , , Java . , :

try {
    engine.eval("throw new java.lang.IllegalArgumentException( 'no cookie!' )" );
} 
catch (ScriptException e) {
    Throwable cause = e.getCause();
    if ( cause != null && cause instanceof IllegalArgumentException ) {
        // ...react explicitly 
    }
    else {
        // ...react generically
    }
0

Source: https://habr.com/ru/post/1753177/


All Articles