2010-08-05 94 views
0

我送了以下AJAX請求:如何從Grails中的AJAX錯誤回調中檢索錯誤消息?

$.ajax({ type: 'POST', 
    data: $(this).parents('form:first').serialize(), url:'/myapp/comment/saveOrUpdate', 
    success: function(data,textStatus) {insertNewComment(data)}, 
    error: function(xhr, textStatus, errorThrown) {alert(xhr.responseText);} 
}) 

...和我控制器操作是這樣的:

class CommentController { 
... 
def saveOrUpdate = { 
    ... 
    if (error) { 
     response.sendError 419, 'You must wait at least 5 minutes before posting a new comment' 
    } 
}} 

不幸的是,我從來沒有看到我在HTTP響應發送消息。相反,我從Tomcat /阿帕奇(或Grails的?)產生錯誤的HTML頁面,看起來像:

<html><head><title>Apache Tomcat/6.0-snapshot - Error report</title> 
</head><body><h1>HTTP Status 419 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>Cannot find message associated with key http.419</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0-snapshot</h3></body></html> 

我怎樣才能繞過產生的錯誤HTML頁面,以便從JavaScript代碼的消息「您檢索必須等待......'?

謝謝你的幫助。

回答

0

您正在設置一個HTTP狀態錯誤,但實際上您正在捕捉業務邏輯問題 - 一個應用程序錯誤。爲什麼不只是設置一個合適的應用程序級別的狀態碼和消息(你自己的設計),並返回那些在Ajax響應(包括剩餘時間)?如果您依賴HTTP錯誤代碼,則可能會在不同的瀏覽器中獲得不同的結果,其中一些在錯誤頁面小於512字節時會劫持錯誤消息。

在你舉的情況下,Apache的發現沒有已知的錯誤信息匹配419

你可以添加一個到您的.htaccess配置:

ErrorDocument 419 /errordocs/419.html 

...然後做出419.html頁說你喜歡的任何東西(並確保頁面超過512字節)。但我敢打賭,使用應用程序級別的狀態代碼就是您要找的。

+0

我已經按照您的建議實施了應用程序級別的狀態代碼。 謝謝。 – fabien7474 2010-08-25 10:40:01