JavaScud | Forum | JIRA | Blog |
  Dashboard > DWR中文文档 > Home > Error Handling
  DWR中文文档 Log In View a printable version of the current page.  
  Error Handling
Added by 黑灵, last edited by 黑灵 on Oct 28, 2006
Labels: 
(None)

错误处理

在1.0版中错误处理规则有些bug,1.1修复了这些错误。

DWR中有一些全局的处理器(一个错误相关的, 叫做errorHandler, 另一个警告相关的, 叫做warningHandler)。DWR会默认指定一些全局处理器。你可以这样的改变全局级别的处理器:

DWREngine.setErrorHandler(handler);

你也可以指定单次调用和批量调用的错误和警告处理。例如,在调用元数据中:

Remote.method(params, { 
callback:function(data) { ... }, 
errorHandler:function(errorString, exception) { ... } 
});

或者,在批量元数据中:

DWREngine.beginBatch(); 
Remote.method(params, function(data) { ... }); 
// 其他的远程调用 
DWREngine.endBatch({ 
errorHandler:function(errorString, exception) { ... } 
});

异常

DWR可以转换异常,这样他们会变成Javascript中的错误(他们可以被抛出,因为这可能在异步调用中发生)。
例如,如果我们远程调用下面的Java类:

public class Remote { 
public String getData() { 
throw new NullPointerException("message"); 
} 
}

那么在Javascript中我们加入下面这些:

function eh(msg) { 
alert(msg); 
} 
{ 
DWREngine.setErrorHandler(eh); 

Remote.getData(function(data) { alert(data); });

结果会通过eh()错误处理器调用alert窗口的,显示消息 – 例如调用异常的getMessage()得到的消息。

找出更多的信息

我们可以把整个异常传地到Javascript中。如果在dwr.xml中加入转换异常本身的能力:

<convert converter="bean" match="my.special.FunkyException"/>

在这里例子中FunkyException被指定,因为它不仅仅包括一个消息,它还包括一些关于异常的额外数据。例如,SQLException包含错误号,SAX异常包含错误的行和列等等。所以我们可以把上面的例如改为:

public class Remote { 
public String getData() { 
Date when = new Date(); 
throw new FunkyException("message", when); 
// FunkyException有一个getWhen()方法 
} 
}

然后在Javascript中是这样的:

function eh(msg, ex) { 
alert(msg + ", date=" + ex.when); 
} 

DWREngine.setErrorHandler(eh); 

Remote.getData(function(data) { alert(data); });

结果会是一个eh()错误处理器调用的alert框,上面有这些信息:"message, date=Mon Jan 01 2008 10:00:00 GMT+0100"

被传递到错误处理器的ex对象会包含异常在服务端的所有属性,但是异常栈信息没有。

Site running on a free Atlassian Confluence Open Source Project License granted to WebWork China. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.3 Build:#808 May 29, 2007) - Bug/feature request - Contact Administrators