Search code examples
javajavascriptexceptiongwtjsni

GWT: Catch native JSNI exception in Java code


I have some logic in native method, which returns sth or null - they are both valid and meaningful states, and I want to throw an exception on method's failure. As it is native JSNI i am not sure how to do that.

So consider method:

public final native <T> T myNativeMethod() /*-{

    //..some code


    //in javascript you can throw anything, not only the exception object:
    throw "something"; 

}-*/;

but how to catch the thrown object?

void test() {
    try {
        myNativeMethod();
    }
    catch(Throwable e) { // what to catch here???
    }
}

Is there any special Gwt Exception Type wrapping "exception objects" thrown from JSNI?


Solution

  • As to Daniel Kurka's answer (and my intuition ;)). My code could then look like that:

    public final native <T> T myNativeMethod() throws JavaScriptException /*-{
    
        //..some code
    
    
        //in javascript you can throw anything it not just only exception object:
        throw "something"; 
    
        //or in another place of code
        throw "something else";
    
        //or:
        throw new (function WTF() {})();
    
    }-*/;
    
    void test() throws SomethingHappenedException, SomethingElseHappenedException, UnknownError {
        try {
            myNativeMethod();
        }
        catch(JavaScriptException e) { // what to catch here???
    
            final String name = e.getName(), description = e.toString(); 
    
            if(name.equalsIgnoreCase("string")) {
    
                if(description.equals("something")) {
                    throw new SomethingHappenedException(); 
                }
                else if(description.equals("something else")) {
                    throw new SomethingElseHappenedException(); 
                }
            }
            else if(name.equals("WTF")) {
                throw new UnknownError();
            }
        }
    }