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?
You have a JSON object of the exception thrown, in the xhr object. Just use
The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'
If someone is here as in 2016 for the answer, use
.fail()
for error handling as.error()
is deprecated as of jQuery 3.0I hope it helps
Although it has been many years since this question is asked, I still don't find
xhr.responseText
as the answer I was looking for. It returned me string in the following format:which I definitely don't want to show to the users. What I was looking for is something like below:
xhr.responseJSON.message
gives me the exact message from the Json Object which can be shown to the users.This is what I did and it works so far in a MVC 5 application.
Controller's return type is ContentResult.
And on client side this is what ajax function looks like
Make sure you're setting
Response.StatusCode
to something other than 200. Write your exception's message usingResponse.Write
, then use.....in your javascript.