2011-12-13 93 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很好。