[英]Servlet Ajax global exception handling
我有一個AJAX調用的全局處理程序
$.ajaxSetup({
error: function(xhr, textStatus, errorThrown) {
//do something
}
});
如果出現錯誤,我的servlet過濾器會發送一個特定的錯誤
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if(somethingwrong()) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unavailableimage");
}
}
你會建議做點什么嗎?
$.ajaxError({
error: function(xhr, textStatus, errorThrown) {
if (xhr.status == 408) {
//doSomething
}
else if xhr.responseText.contains("unavailableimage"){
//doSomething
}
}
});
因為我認為每個瀏覽器中的responseText都不同。
響應正文可以通過xhr.responseText
。
但是, HttpServletResponse#sendError()
(< - 單擊鏈接以自己讀取Javadoc)將使用servletcontainer的默認錯誤頁面模板或您在web.xml
定義的自定義錯誤頁面模板。 這是一個HTML文檔,因此您必須自己解析。
根據您對其他答案的評論,您似乎正在使用Tomcat並檢索其默認錯誤頁面; 該消息可用作第二個<p>
第一個<u>
元素。 所以這應該做:
var errorMessage = $(xhr.responseText).filter('p:eq(1)').find('u').text();
if (errorMessage == 'unavailableimage') {
// ...
}
您只需要記住,這種方式與(默認)錯誤頁面的標記緊密相關。 更好的是不使用HttpServletResponse#sendError()
,但只需通過HttpServletResponse#setStatus()
設置狀態(< - 是,單擊它以讀取javadoc,答案就在那里)並將錯誤消息寫入響應正文:
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("unavailableimage");
這樣xhr.responseText
就完全unavailableimage
。
if (xhr.responseText == 'unavailableimage') {
// ...
}
在我的項目中,我正在使用此函數來調試ajax:
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internal Server Error.\n'+x.responseText););
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
所以使用你的代碼,你可以測試x.responseText
包含'unavailableimage',但是通過錯誤代碼測試它並且錯誤消息更好;)
獲取響應錯誤消息的另一種方法是使用: var responseText = $.httpData(xhr)
具體取決於您的JQuery版本(<1.5.2)
或者使用json: var responseText = $.parseJSON(x.responseText);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.