2017  Kodetalk | Feedback | Privacy Policy | Terms | About

jQuery Ajax error handling, show custom exception messages

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()) {
      type: "POST",
      url: "saveuser.do",
      dataType: "html",
      data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
      success: function (response) {
        alert("Details saved successfully!!!");
      error: function (xhr, ajaxOptions, 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?


We can parse out the message what we are sending from the server and display the error message to the user without the stack trace.

error: function (response) {
      var r = jQuery.parseJSON(response.responseText);
      alert("Message: " + r.Message);
      alert("StackTrace: " + r.StackTrace);
      alert("ExceptionType: " + r.ExceptionType);

Answer is