Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Throw Java exception from Javascript

1,512 views
Skip to first unread message

ian

unread,
Mar 5, 2009, 3:32:12 PM3/5/09
to
Is it possible to throw a Java exception (i.e. an object that extends
java.lang.Exception) from Javascript and handle the exception in Java
code?

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

Attila Szegedi

unread,
Mar 6, 2009, 3:27:31 AM3/6/09
to ian, dev-tech-js-...@lists.mozilla.org
Well, this is an artifact of the Sun's embedding of Rhino in
javax.script.* framework; we can't really help you with that.

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

0 new messages