[英]How do I get the server-side exception message with GWT?
我試過了
public void onFailure(Throwable caught) {
Throwable cause = caught.getCause();
String causeStr = (cause==null) ? "" : ", "+cause.getMessage();
errorLabel.setText(SERVER_ERROR + ": " + caught.getMessage() + causeStr);
但是原因始終為null並被caught.getMessage()
始終等於非常通用的500 The call failed on the server; see server log for details
500 The call failed on the server; see server log for details
。 我想從服務器拋出IllegalArgumentExceptions並能夠在客戶端上顯示它:
throw new IllegalArgumentException("Email address is invalid.");
您的例外需要可序列化才能通過電纜傳輸。
此外,最佳做法是:您應該有兩種異常類型:
這樣,您將在日志中寫入系統異常並將業務異常發送回用戶
您可以使用com.google.gwt.core.client.GWT.UncaughtExceptionHandler
捕獲服務器上的異常,然后拋出自己的異常
實現Serializable
,以及
在源文件夾中定義,該文件夾是客戶端可以訪問的(並針對該客戶端進行編譯)。
您還可以重寫RequestFactoryServlet
並將其傳遞給自定義異常處理程序:
public class CustomRequestFactoryServlet extends RequestFactoryServlet {
private static class ApplicationExceptionLogger implements ExceptionHandler {
private final Logger log = LoggerFactory.getLogger(ApplicationExceptionLogger.class);
@Override
public ServerFailure createServerFailure(Throwable throwable) {
log.error("Server Error", throwable);
return new ServerFailure(throwable.getMessage(), throwable.getClass().getName(), throwable.getStackTrace().toString(), true);
}
}
public CustomRequestFactoryServlet() {
super(new ApplicationExceptionLogger());
}
}
在web.xml ::
<servlet>
<servlet-name>requestFactoryServlet</servlet-name>
<servlet-class>com.myvdm.server.CustomRequestFactoryServlet</servlet-class>
</servlet>
我還發現您可以發送回Google UmbrellaException,但是您必須對其進行實例化,因為它僅在構造函數中使用Sets:
public String getUserId () throws Exception {
Set<Throwable> s = new HashSet<Throwable>(Arrays.asList(new IllegalArgumentException("Hidey hidey ho!")));
if (true) throw new com.google.gwt.event.shared.UmbrellaException(s);
public void onFailure(Throwable caught) {
log.severe("fetchUserName(), Could not fetch username: " + caught.getMessage());
Mon Oct 14 12:05:28 EDT 2013 com.example.client.Login
SEVERE: fetchUserName(), Could not fetch username: Exception caught: Hidey hidey ho!
我最喜歡Zied和Fred的答案,因為它們是最簡單,最透明的。 但是,無需使用UncaughtExceptionHandler或創建SystemExceptions,因此它甚至可以更加簡單。 只需捕獲異常,然后重新包裝並拋出即可。 無需亂扔服務器接口(帶有您自己的異常)。 像OutOfMemoryError這樣的嚴重錯誤將由GWT正常處理。 比我的其他答案還簡單的實例化。 GWT已經具有onSuccess/onFailure
通過/失敗處理程序,因此無需使用特殊的返回值重新檢查onSuccess
內的失敗。 但是,到達onFailure
的唯一方法是使用Exception,因此即使布爾值就足夠了,也需要使用Exception來向客戶端處理程序指示錯誤。
package com.example.shared;
import java.io.Serializable;
public class MyException extends Exception implements Serializable {
private static final long serialVersionUID = 1104312904865934899L;
public MyException() {}
public MyException (String s) {
super(s);
}
}
public void cancelSend() throws MyException {
throw new MyException("Because I said so");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.