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()) {
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?
Make sure you're setting Response.StatusCode
to something other than 200. Write your exception's message using Response.Write
, then use...
xhr.responseText
..in your javascript.
Controller:
public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
response.Write(filterContext.Exception.Message);
response.ContentType = MediaTypeNames.Text.Plain;
filterContext.ExceptionHandled = true;
}
}
[ClientErrorHandler]
public class SomeController : Controller
{
[HttpPost]
public ActionResult SomeAction()
{
throw new Exception("Error message");
}
}
View script:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
ServerSide:
doPost(HttpServletRequest request, HttpServletResponse response){
try{ //logic
}catch(ApplicationException exception){
response.setStatus(400);
response.getWriter().write(exception.getMessage());
//just added semicolon to end of line
}
}
ClientSide:
jQuery.ajax({// just showing error property
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
}
}
});
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.
$("div#errorcontainer")
.ajaxError(
function(e, x, settings, exception) {
var message;
var statusErrorMap = {
'400' : "Server understood the request, but request content was invalid.",
'401' : "Unauthorized access.",
'403' : "Forbidden resource can't be accessed.",
'500' : "Internal server error.",
'503' : "Service unavailable."
};
if (x.status) {
message =statusErrorMap[x.status];
if(!message){
message="Unknown Error n.";
}
}else if(exception=='parsererror'){
message="Error.nParsing JSON Request failed.";
}else if(exception=='timeout'){
message="Request Time out.";
}else if(exception=='abort'){
message="Request was aborted by the server";
}else {
message="Unknown Error n.";
}
$(this).css("display","inline");
$(this).html(message);
});
链接地址: http://www.djcxy.com/p/17330.html