2011-12-13 102 views
1

我試圖編寫一個代碼,該代碼將捕獲由ServiceImpl引發的PhoneNumberInUseException,但下面的代碼始終適用於else語句。使用GWT處理自定義異常

@Override 
      public void onFailure(Throwable caught) { 
       Window.alert("Failed create account."); 
       if (caught instanceof PhoneNumberInUseException) { 
        Window.alert("Sorry, but the phone number is already used."); 
       } else { 
        Window.alert(caught.toString()); 
       } 

      } 

PhoneNumberInUseException extends RuntimeException

現在我只是顯示這個通過Window.alert,但是我會做客戶端邏輯處理異常,這就是爲什麼我不能簡單地用IllegalArgumentException這可以很好地將異常字符串從服務器傳遞到客戶端。

我錯過了什麼嗎?

回答

0

我不得不從IllegalArgumentException,而不只是Exception延長PhoneNumnberInUseException並使其Serializable,我不知道這是正確的做法,但:

public class PhoneNumnberInUseException extends IllegalArgumentException implements Serializable{ 
    public PhoneNumnberInUseException(){ 
     super(); 
    } 
    public PhoneNumnberInUseException(String msg) { 
     super(msg); 
    } 
} 
+0

實際上,你可能正好保持你的代碼,因爲它並且只是聲明你的RPC方法拋出了這個異常:'public void doSomething(Object someObject)throws PhoneNumberInUseException;'。如果GWT通過'throws'顯式聲明,那麼GWT只會將'RuntimeException'傳播給客戶端。 –

+0

@ChrisCashwell我看到,我使用RuntimeException的原因是因爲我需要在if-else語句內引發異常,而如果從Exception擴展,我得到語法錯誤。 – xybrek

+0

更新了我的答案。 –

3

如果您PhoneNumberInUseException類看起來是這樣的:

public class PhoneNumberInUseException extends RuntimeException { 

    public PhoneNumberInUseException() { 
     super(); 
    } 
} 

,你就這樣把它扔在服務:

throw new PhoneNumberInUseException(); 

那麼你的代碼應該被正確地射擊。那是當然的,假設你的服務已經宣佈,它拋出PhoneNumberInUseException,就像這樣:

public interface SomeService extends RemoteService { 
    void doSomething(Object someObject) throws PhoneNumberInUseException; 
} 

public interface SomeServiceAsync { 
    void doSomething(Object someObject, AsyncCallback callback); 
} 

public class SomeServiceImpl extends RemoteServiceServlet implements SomService { 
    public void doSomething(Object someObject) throws PhoneNumberInUseException { 
     if(somethingHappened) { 
      throw new PhoneNumberInUseException(); 
     } else { 
      doSomethingCool(); 
     } 
    } 
} 

如果您確定一切應該工作正常後,你可能想要把一個斷點上line

if (caught instanceof PhoneNumberInUseException) 

並找出caught的等級是什麼。如果它不是而不是PhoneNumberInUseException,你可能還沒有read the documentation很好。