簡體   English   中英

GWT:在Java代碼中捕獲本機JSNI異常

[英]GWT: Catch native JSNI exception in Java code

我在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"; 

}-*/;

但如何抓住拋出的物體?

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

是否有任何特殊的Gwt異常類型包裝從JSNI拋出的“異常對象”?

來自gwt文檔:

在執行普通Java代碼或JSNI方法中的JavaScript代碼期間,可能會拋出異常。 當JSNI方法中生成的異常向上傳播調用堆棧並被Java catch塊捕獲時,拋出的JavaScript異常在捕獲時被包裝為JavaScriptException對象。 此包裝器對象僅包含發生的JavaScript異常的類名和描述。 建議的做法是處理JavaScript代碼中的JavaScript異常和Java代碼中的Java異常。

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

至於丹尼爾庫爾卡的答案(和我的直覺;))。 我的代碼可能看起來像那樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM