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

例如,如果我想通过抛出新的ApplicationException(“用户名已经存在”),通过Struts在服务器端抛出异常;,我想在jQueryAJAX错误消息中捕获此消息(“用户名已存在”)。

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

在错误回调中的第二个警报中,我向thrownError发出警报,我得到了未定义,xhr.status代码为500。

我不知道我错在哪里。我可以做什么来解决这个问题?


当前回答

我相信Ajax响应处理程序使用HTTP状态代码来检查是否存在错误。

因此,如果您只是在服务器端代码上抛出一个Java异常,但HTTP响应没有500状态代码,jQuery(或者在本例中可能是XMLHttpRequest对象)将假设一切正常。

我这么说是因为我在ASP.NET中遇到了类似的问题,我抛出了ArgumentException(“不知道该怎么做…”)之类的东西,但错误处理程序没有启动。

然后,无论是否有错误,我都将Response.StatusCode设置为500或200。

其他回答

通用/可重复使用的解决方案

这个答案是为将来遇到这个问题的所有人提供的参考。解决方案由两部分组成:

在服务器上验证失败时引发的自定义异常ModelStateException(当我们使用数据注释并使用强类型控制器操作参数时,模型状态报告验证错误)自定义控制器操作错误筛选器HandleModelStateExceptionAttribute,它捕获自定义异常并返回HTTP错误状态,主体中包含模型状态错误

这为jQueryAjax调用提供了最佳的基础设施,以便在成功和错误处理程序中充分发挥其潜力。

客户端代码

$.ajax({
    type: "POST",
    url: "some/url",
    success: function(data, status, xhr) {
        // handle success
    },
    error: function(xhr, status, error) {
        // handle error
    }
});

服务器端代码

[HandleModelStateException]
public ActionResult Create(User user)
{
    if (!this.ModelState.IsValid)
    {
        throw new ModelStateException(this.ModelState);
    }

    // create new user because validation was successful
}

整个问题在这篇博客文章中有详细介绍,您可以在其中找到在应用程序中运行此功能的所有代码。

您需要将responseText转换为JSON。使用JQuery:

jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);

如果有人像2016年一样在这里寻找答案,请使用.fail()进行错误处理,因为.error()在jQuery 3.0中已被弃用

$.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    //handle error here
  })

我希望这有帮助

在xhr对象中有一个抛出异常的JSON对象。只需使用

alert(xhr.responseJSON.Message);

JSON对象公开了其他两个财产:“ExceptionType”和“StackTrace”

这就是我所做的,它目前在MVC 5应用程序中运行。

控制器的返回类型为ContentResult。

public ContentResult DoSomething()
{
    if(somethingIsTrue)
    {
        Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
        Response.Write("My Message");
        return new ContentResult();
    }

    //Do something in here//
    string json = "whatever json goes here";

    return new ContentResult{Content = json, ContentType = "application/json"};
}

在客户端,这是ajax函数的样子

$.ajax({
    type: "POST",
    url: URL,
    data: DATA,
    dataType: "json",
    success: function (json) {
        //Do something with the returned json object.
    },
    error: function (xhr, status, errorThrown) {
        //Here the status code can be retrieved like;
        xhr.status;

        //The message added to Response object in Controller can be retrieved as following.
        xhr.responseText;
    }
});