【问题标题】:GWT: Catch native JSNI exception in Java codeGWT:在 Java 代码中捕获本机 JSNI 异常
【发布时间】:2012-07-17 20:20:54
【问题描述】:

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

所以考虑方法:

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

    //..some code


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

}-*/;

但是如何捕捉抛出的物体?

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

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

【问题讨论】:

    标签: java javascript exception gwt jsni


    【解决方案1】:

    来自 gwt 文档:

    在执行任何普通 Java 的过程中都可能引发异常 代码或 JSNI 方法中的 JavaScript 代码。当异常 在 JSNI 方法中生成的会向上传播调用堆栈并且是 被 Java catch 块捕获,抛出的 JavaScript 异常是 在被捕获时包装为 JavaScriptException 对象。这 包装器对象只包含类名和描述 发生的 JavaScript 异常。推荐的做法是 处理 JavaScript 代码中的 JavaScript 异常和 Java 中的异常 Java 代码。

    这里是完整的参考: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#exceptions

    【讨论】:

    • 你的意思是 com.google.gwt.core.client.JavaScriptException?可以肯定:)
    • 还有一个问题:上面提到的“描述”是用 getMessage() 或 toString() 检索的?
    • 基本上处理你在 JavaScript 中的 JavaScript 异常和在 Java 中的 Java 异常。如果你真的需要抛出一些东西,你可以在你的 Java 代码中捕获 JavaScriptException
    • 我知道您在上面的文档中有一个建议来处理 jsni 中的 js 异常,但在这种情况下,我想故意忽略它;)。
    【解决方案2】:

    至于 Daniel Kurka 的回答(以及我的直觉 ;))。我的代码可能看起来像这样:

    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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2019-12-28
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      相关资源
      最近更新 更多