I have some jQuery code that makes a REST call to a Java back end. Processing of the back end function could encounter an Exception. What is the best way to get this information back up to Javascript? In a test I caught the exception in Java and set the HTTP status code to 500. This caused the $.ajax error handler to be called, as expected. the args to the error handler don't really contain any useful information. I'd ideally like to propagate the Exception.getMessage() string back to the error handler somehow, but don't know how.
function handleClick() {
var url = '/backend/test.json';
$.ajax({
type: "POST",
url: url,
cache: false,
dataType: "json",
success: function(data){
alert("it worked");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR);
alert(textStatus); // this comes back as "error"
alert(errorThrown); // this comes back as "undefined"
}
});
}
Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request.
ajax returns, which is a jqXHR object that conforms to the promise interface. If there is a failure, the outer fail function is invoked. The outer fail function is also invoked if the processData function fails. When both the getData and processData functions are successful, the outer done method is invoked.
The jQuery XMLHttpRequest (jqXHR) object returned by $. ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.
ajax({ type: "GET", url: "http://localhost:8084/Shade/src/java/mail/Main.execute", data: val, async: true, cache: false, success: function (msg) { alert("hi"); $(". col-1"). html(msg); });
I was able to send a custom error message (java String) back to a jQuery based client this way. I think my custom message can be replaced with the exception info you want/need
public static void handleRuntimeException(Exception ex, HttpServletResponse
response,String message) {
logger.error(ex);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write(message);
response.flushBuffer();
}
displayError:function(jqXHR, textStatus, errorThrown){
if(jqXHR.responseText !== ''){
alert(textStatus+": "+jqXHR.responseText);
}else{
alert(textStatus+": "+errorThrown);
}
}
Hope this helps/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With