Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");
, I want to catch this message ('user name already exists') in the jQuery AJAX error message.
jQuery("#save").click(function () {
if (jQuery('#form').jVal()) {
jQuery.ajax({
type: "POST",
url: "saveuser.do",
dataType: "html",
data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
jQuery("#usergrid").trigger("reloadGrid");
clear();
alert("Details saved successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
On the second alert, where I alert the thrown error, I am getting undefined
and the status code is 500.
I am not sure where I am going wrong. What can I do to fix this problem?
If making a call to asp.net, this will return the error message title:
I didn't write all of formatErrorMessage myself but i find it very useful.
I found this to be nice because I could parse out the message I was sending from the server and display a friendly message to the user without the stacktrace...
A general/reusable solution
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
ModelStateException
that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)HandleModelStateExceptionAttribute
that catches custom exception and returns HTTP error status with model state error in the bodyThis provides the optimal infrastructure for jQuery Ajax calls to use their full potential with
success
anderror
handlers.Client side code
Server side code
The whole problem is detailed in this blog post where you can find all the code to run this in your application.
jQuery.parseJSON is useful for success and error.
I believe the Ajax response handler uses the HTTP status code to check if there was an error.
So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.
I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.
I then set the
Response.StatusCode
to either 500 or 200 whether I had an error or not.You need to convert the
responseText
to JSON. Using JQuery: