GWT:在Java代码中捕获本机JSNI异常

Tom*_*wel 4 javascript java gwt exception jsni

我在native方法中有一些逻辑,它返回sth或null - 它们都是有效和有意义的状态,我想在方法失败时引发异常.由于它是原生JSNI,我不知道该怎么做.

所以考虑方法:

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

    //..some code


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

}-*/;
Run Code Online (Sandbox Code Playgroud)

但如何抓住抛出的物体?

void test() {
    try {
        myNativeMethod();
    }
    catch(Throwable e) { // what to catch here???
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有任何特殊的Gwt异常类型包装从JSNI抛出的"异常对象"?

Dan*_*rka 6

来自gwt文档:

在执行普通Java代码或JSNI方法中的JavaScript代码期间,可能会抛出异常.当JSNI方法中生成的异常向上传播调用堆栈并被Java catch块捕获时,抛出的JavaScript异常在捕获时被包装为JavaScriptException对象.此包装器对象仅包含发生的JavaScript异常的类名和描述.建议的做法是处理JavaScript代码中的JavaScript异常和Java代码中的Java异常.

以下是完整的参考资料:http: //www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#exceptions

  • 基本上处理JavaScript中的JavaScript异常和Java中的Java异常.如果你真的需要抛出一些东西,你可以在Java代码中捕获JavaScriptException (2认同)

Tom*_*wel 5

至于丹尼尔库尔卡的答案(和我的直觉;)).我的代码可能看起来像那样:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)