I am implementing an interface in my Javascript code, and would like
to throw an exception from a method in my Javascript code.
When I execute my Java code (which executes Javascript code that
throws an exception) I keep seeing a
java.lang.reflect.UndeclaredThrowableException caused by
java.security.PrivilegedActionException caused by
javax.script.ScriptException.
I'd like to see the exception that I threw from Javascript instead of
the UndeclaredThrowableException.
Here's my throw statement in Javascript:
throw new com.acme.AcmeRuntimeException();
Any help would be great. Thanks!
Ian
However, if you throw anything in a script (remember, in JS, you can
throw _any_ value) , it'll end up in Java as a JavaScriptException.
The fact that the object you threw is a Java exception (or, rather, a
Rhino wrapper for a Java object, namely a NativeJavaObject) is
irrelevant. Here's roughly a kind of a catch block I use in some of my
Rhino-embedding code:
catch(JavaScriptException e)
{
Throwable javaThrowable = e;
// See if it's nontrivally wrapping either an exception
// thrown from Java method (in which case it's a NativeError
// wrapping a NativeJavaObject, wrapping a Throwable) or a Java
// exception directly thrown in the script (i.e.
// "throw new java.lang.Exception()" executed in script), in
// which case it is a NativeJavaObject wrapping a Throwable.
Object val = e.getValue();
// Unwrap NativeError to NativeJavaObject first, if possible
if(val instanceof Scriptable)
{
Object njo = ScriptableObject.getProperty(((Scriptable)val),
"rhinoException");
if(njo instanceof NativeJavaObject)
{
val = njo;
}
else
{
njo = ScriptableObject.getProperty(((Scriptable)val),
"javaException");
if(njo instanceof NativeJavaObject)
{
val = njo;
}
}
}
// If val is a NativeJavaObject, unwrap to the Java object
if(val instanceof NativeJavaObject)
{
val = ((NativeJavaObject)val).unwrap();
}
// If val is now a Throwable, it's the one we were looking for.
// Otherwise, it'll remain set to the JavaScriptException
if(val instanceof Throwable)
{
javaThrowable = (Throwable)t;
}
... do something with javaThrowable here...
}
Hope that helps.
Attila.
--
home: http://www.szegedi.org
twitter: http://twitter.com/szegedi
weblog: http://constc.blogspot.com