I have a global handler for my AJAX calls
$.ajaxSetup({
error: function(xhr, textStatus, errorThrown) {
//do something
}
});
And in case of an error my servlet filter sends a specifc error
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if(somethingwrong()) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unavailableimage");
}
}
Would you recommend to do something like
$.ajaxError({
error: function(xhr, textStatus, errorThrown) {
if (xhr.status == 408) {
//doSomething
}
else if xhr.responseText.contains("unavailableimage"){
//doSomething
}
}
});
Because I think the responseText is different in every browser.
The response body is available by
xhr.responseText.However, the
HttpServletResponse#sendError()( <– click the link to read the Javadoc yourself) will use the servletcontainer’s default error page template or your custom error page template as you’ve definied inweb.xml. This is a HTML document which you thus have to parse yourself.As per your comment on the other answer, you seem to be using Tomcat and retrieving its default error page; the message is available as first
<u>element of the second<p>. So this should do:You only need to keep in mind that you’re this way tight coupled to the markup of the (default) error page. Better is to not use
HttpServletResponse#sendError(), but just set the status byHttpServletResponse#setStatus()( <– yes, click it to read javadoc, the answer was in there) and write the error message to the response body yourself:This way the
xhr.responseTextis exactlyunavailableimage.