2016-07-07 80 views
0

我想在Richfaces中使用onerror屬性來處理我的ajax請求的異常。對於我已經使用Richfaces 4.5中的onError屬性的使用

<a4j:commandButton value="OK" 
actionListener="#{aBean.handler()}" 
onerror="showNotification();"> 

,在我管理的Bean:

ABean{ 
    public void handler(){ 
     throw new SomeException("Error to the browser"); 
    } 
} 

雖然,我有我的處理程序拋出的異常,我showNotification()不會被調用。

我可以使用onerror屬性處理我的應用程序級別異常嗎?任何關於這個主題的指針或例子都非常感謝。

+0

您的意思是'actionListener =「#{aBean.handler}」''without'()'? –

+0

我在兩種方式#{aBean.handler()}或#{aBean.handler}中看不到任何區別。我們不? –

+0

是的,它是這樣的情況,但也看我的答案的結尾。 –

回答

2

docs您可以閱讀onerror屬性適用於:

當錯誤請求結果

這基本上意味着,請求必須HTTP錯誤結束。例如HTTP 500,這可能意味着該服務器目前無法使用。

它(JAVA)例:

public void handler2() throws IOException { 
    FacesContext context = FacesContext.getCurrentInstance(); 
    context.getExternalContext().responseSendError(HttpServletResponse.SC_NOT_FOUND, 
      "404 Page not found!"); 
    context.responseComplete(); 
} 

a4j:commandButton(XHTML)

<a4j:commandButton value="OK" actionListener="#{bean.handler2}" 
    onerror="console.log('HTTP error');" /> 

在JavaScript控制檯,你會看到 「HTTP錯誤」。

在任何其他情況下的例外oncomplete由於AJAX請求成功結束,因此將觸發代碼。所以如果你不想對代碼中的異常作出反應,你必須自己處理。有很多方法可以做到這一點。我用這個:

public boolean isNoErrorsOccured() { 
    FacesContext facesContext = FacesContext.getCurrentInstance(); 
    return ((facesContext.getMaximumSeverity() == null) || 
       (facesContext.getMaximumSeverity() 
        .compareTo(FacesMessage.SEVERITY_INFO) <= 0)); 
} 

而且我oncomplete看起來是這樣的:

<a4j:commandButton value="OK" execute="@this" actionListener="#{bean.handler1}" 
    oncomplete="if (#{facesHelper.noErrorsOccured}) 
     { console.log('success'); } else { console.log('success and error') }" /> 

與處理程序是這樣的:

public void handler1() { 
    throw new RuntimeException("Error to the browser"); 
} 

在JavaScript控制檯,你會看到 「成功和錯誤」。


BTW。最好寫actionListener="#{bean.handler3}"而不是actionListener="#{bean.handler3()}"。原因背後:

public void handler3() { // will work 
    throw new RuntimeException("Error to the browser"); 
} 

// the "real" actionListener with ActionEvent won't work and 
// method not found exception will be thrown 
public void handler3(ActionEvent e) { 
    throw new RuntimeException("Error to the browser"); 
} 
+0

謝謝埃米爾。我只是想從處理程序方法發送異常詳細信息消息/數據到瀏覽器作爲錯誤響應的一部分。所以我可以在console.log(exceptionDetails)這樣的onerror屬性中使用它;我用onerror =「console(event.data)」,但我看到在控制檯中未定義。 –

+0

很高興我能幫到你。但這是另一個問題。如果你喜歡我對_original_問題的回答,請接受它。如果您有不同的問題,請在不同的主題中提出。 (你不能使用'事件。數據「,如果你還沒有設置它的話。) –

相關問題