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?
ServerSide:
ClientSide:
Generic Ajax Error Handling
If I need to do some generic error handling for all the ajax requests. I will set the ajaxError handler and display the error on a div named errorcontainer on the top of html content.
Throw a new exception on server using:
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
I believe that the StatusDescription is returned to the Ajax call...
Example:
This is probably caused by the JSON field names not having quotation marks.
Change the JSON structure from:
to:
If there is any form is submit with validate
simply use the rest of the code
... ... });
First we need to set <serviceDebug includeExceptionDetailInFaults="True" /> in web.config:
In addition to that at jquery level in error part you need to parse error response that contains exception like:
Then using r.Message you can actully show exception text.
Check complete code: http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html
Controller:
View script: