有什么方法可以在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。

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


当前回答

使用以下命令在服务器上引发新异常:

Response.StatusCode=500

Response.StatusDescription=例如消息()

我认为StatusDescription返回到Ajax调用。。。

例子:

        Try

            Dim file As String = Request.QueryString("file")

            If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")

            Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()

            sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)

            file = IO.Path.Combine(sTmpFolder, file)

            If IO.File.Exists(file) Then

                IO.File.Delete(file)

            End If

        Catch ex As Exception

            Response.StatusCode = 500

            Response.StatusDescription = ex.Message()

        End Try

其他回答

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

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

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

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

这可能是由于JSON字段名没有引号导致的。

更改JSON结构:

{welcome:"Welcome"}

to:

{"welcome":"Welcome"}

使用以下命令在服务器上引发新异常:

Response.StatusCode=500

Response.StatusDescription=例如消息()

我认为StatusDescription返回到Ajax调用。。。

例子:

        Try

            Dim file As String = Request.QueryString("file")

            If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")

            Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()

            sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)

            file = IO.Path.Combine(sTmpFolder, file)

            If IO.File.Exists(file) Then

                IO.File.Delete(file)

            End If

        Catch ex As Exception

            Response.StatusCode = 500

            Response.StatusDescription = ex.Message()

        End Try

首先,我们需要在web.config中设置<serviceDebug includeExceptionDetailInFaults=“True”/>:

<serviceBehaviors> 
 <behavior name=""> 
  <serviceMetadata httpGetEnabled="true" /> 
    **<serviceDebug includeExceptionDetailInFaults="true" />** 
 </behavior> 
</serviceBehaviors>

除了jquery级别的错误部分,您还需要解析包含异常的错误响应,如:

.error(function (response, q, t) { 
  var r = jQuery.parseJSON(response.responseText); 
}); 

然后使用r.Message,您可以实际显示异常文本。

检查完整代码:http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html

尽管这个问题已经问了很多年了,但我仍然没有找到xhr.responseText作为我一直在寻找的答案。它以以下格式返回字符串:

"{"error":true,"message":"The user name or password is incorrect"}"

我绝对不想向用户展示。我要找的东西如下:

alert(xhr.responseJSON.message);

xhr.responseJSON.message为我提供了Json对象的确切消息,该消息可以显示给用户。