jQuery Ajax错误处理,显示自定义异常消息

有什么方法可以在我的jQuery AJAX错误消息中显示自定义异常消息作为警报?

例如,如果我想通过throw new ApplicationException("User name already exists");通过Struts在服务器端抛出异常throw new ApplicationException("User name already exists"); ,我想在jQuery AJAX错误消息中捕获此消息('用户名已存在')。

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);
      }
    });
  }
});

在第二次提醒中,我提醒引发的错误,我得到undefined的状态代码为500。

我不知道我哪里出错了。 我能做些什么来解决这个问题?


请确保您将Response.StatusCode设置为200以外的值。使用Response.Write编写您的异常消息,然后使用...

xhr.responseText

..在你的JavaScript。


控制器:

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");
    }
}

查看脚本:

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

服务器端:

     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

           }
 }

客户端:

 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");
               }
          }
    }); 

通用Ajax错误处理

如果我需要为所有的ajax请求做一些通用的错误处理。 我将设置ajaxError处理程序,并将错误显示在html内容顶部的名为errorcontainer的div上。

$("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/17329.html

上一篇: jQuery Ajax error handling, show custom exception messages

下一篇: What is the difference between application server and web server?