Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
Tomasz Gawel Avatar asked Dec 21 '22 18:12

Tomasz Gawel


2 Answers

From the gwt docs:

An exception can be thrown during the execution of either normal Java code or the JavaScript code within a JSNI method. When an exception generated within a JSNI method propagates up the call stack and is caught by a Java catch block, the thrown JavaScript exception is wrapped as a JavaScriptException object at the time it is caught. This wrapper object contains only the class name and description of the JavaScript exception that occurred. The recommended practice is to handle JavaScript exceptions in JavaScript code and Java exceptions in Java code.

Here is the complete reference: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#exceptions

like image 175
Daniel Kurka Avatar answered Dec 23 '22 06:12

Daniel Kurka


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();
        }
    }
}
like image 36
Tomasz Gawel Avatar answered Dec 23 '22 08:12

Tomasz Gawel