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

708 ajax jquery custom-exceptions

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

例如,如果我想通过Struts by 在服务器端抛出异常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);
      }
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

在第二个警报,我警告抛出的错误,我得到undefined,状态代码是500.

我不确定我哪里出错了.我该怎么做才能解决这个问题?

Spr*_*tar 345

确保设置Response.StatusCode为200以外的其他内容.使用编写例外消息Response.Write,然后使用...

xhr.responseText
Run Code Online (Sandbox Code Playgroud)

..在你的JavaScript中.

  • 这仍然是2年半后这样做的正确方法... :)我进一步实际上返回了我自己的错误JSON对象,可以处理单个或多个错误,非常适合服务器端表单验证. (9认同)
  • 仅当您确保设置了元类型时才设置xhr.responseJSON(例如"Content-type:application/json").这是我刚刚遇到的问题; responseText已设置 - responseJSON未设置. (5认同)
  • 我现在在2014年.JSON占主导地位的时代.所以我使用`xhr.responseJSON`.:d (3认同)

小智 214

控制器:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

查看脚本:

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

  • 这不是问题的"正确"答案,但它肯定会显示更高级别的问题解决方案......很好! (12认同)
  • 我相信你还应该将*response.StatusCode = 500;*行添加到OnException方法中. (6认同)
  • 我改编了这个 - 因为我想要500状态代码,但是在状态描述中有异常消息(而不是"内部服务器错误") - `response.StatusCode =(int)HttpStatusCode.InternalServerError;`和`response.StatusDescription = filterContext.Exception.Message;` (4认同)
  • 如果您使用的是IIS7或更高版本,则可能需要添加:response.TrySkipIisCustomErrors = true; (4认同)
  • 我正在做类似的事情.如果在开发盒上完成所有操作,它可以正常工作.如果我尝试从网络上的其他框连接,xhr.responseText包含通用错误页面html而不是我的自定义消息,请参阅http://stackoverflow.com/questions/3882752/returning-a-response-on-error使用-ASP净MVC-和jQuery的-in-Ajax的呼叫 (3认同)

San*_*ngi 98

服务器端:

     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

           }
 }
Run Code Online (Sandbox Code Playgroud)

客户端:

 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");
               }
          }
    }); 
Run Code Online (Sandbox Code Playgroud)

通用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);
                 });
Run Code Online (Sandbox Code Playgroud)


Syd*_*ney 81

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

jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);
Run Code Online (Sandbox Code Playgroud)

  • +1'因为这是目前这个问题的唯一正确答案!您可以调用"jsonValue.Message"来获取异常消息. (5认同)
  • 实际上它不是正确的答案,因为问题没有询问JSON,并且示例请求特别要求HTML作为响应. (2认同)
  • 解析后的 JSON 对象可通过 jqXHR 对象的 responseJSON 属性获得。所以不需要解析responseText属性。你可以这样做: console.log( jqXHR.responseJSON.Message) (2认同)

Sam*_*nes 36

如果调用asp.net,这将返回错误消息标题:

我自己并没有编写所有的formatErrorMessage,但我发现它非常有用.

function formatErrorMessage(jqXHR, exception) {

    if (jqXHR.status === 0) {
        return ('Not connected.\nPlease verify your network connection.');
    } else if (jqXHR.status == 404) {
        return ('The requested page not found. [404]');
    } else if (jqXHR.status == 500) {
        return ('Internal Server Error [500].');
    } else if (exception === 'parsererror') {
        return ('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
        return ('Time out error.');
    } else if (exception === 'abort') {
        return ('Ajax request aborted.');
    } else {
        return ('Uncaught Error.\n' + jqXHR.responseText);
    }
}


var jqxhr = $.post(addresshere, function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) { 

    var responseTitle= $(xhr.responseText).filter('title').get(0);
    alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) ); 
})
Run Code Online (Sandbox Code Playgroud)


Cen*_*raz 22

这就是我所做的,它到目前为止在MVC 5应用程序中工作.

Controller的返回类型是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"};
}
Run Code Online (Sandbox Code Playgroud)

在客户端,这就是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;
    }
});
Run Code Online (Sandbox Code Playgroud)


Lea*_*ner 18

如果有人在2016年作为答案,请使用jQuery 3.0中不推荐使用.fail()的错误处理.error()

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

我希望它有所帮助

  • 据我所知,jQuery 3.0中不推荐使用jqXHR.error()(实际上已将其删除),但是据我所知,不赞成对$ .ajax()的`error`和`success`回调。 (2认同)

Rob*_*nik 16

一般/可重用的解决方案

这个答案是为了将来参考所有遇到这个问题的人提供的.解决方案包括两件事:

  1. ModelStateException在服务器上验证失败时抛出的自定义异常(当我们使用数据注释并使用强类型控制器操作参数时,模型状态报告验证错误)
  2. 自定义控制器操作错误筛选器 HandleModelStateExceptionAttribute捕获自定义异常并返回HTTP错误状态,并在正文中显示模型状态错误

这为jQuery Ajax调用提供了最佳基础结构,以充分利用它们successerror处理程序.

客户端代码

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

服务器端代码

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

    // create new user because validation was successful
}
Run Code Online (Sandbox Code Playgroud)

整个问题在本博文中详细介绍,您可以在其中找到在您的应用程序中运行此代码的所有代码.


cra*_*ond 14

我发现这很好,因为我可以解析我从服务器发送的消息,并在没有堆栈跟踪的情况下向用户显示友好消息...

error: function (response) {
      var r = jQuery.parseJSON(response.responseText);
      alert("Message: " + r.Message);
      alert("StackTrace: " + r.StackTrace);
      alert("ExceptionType: " + r.ExceptionType);
}
Run Code Online (Sandbox Code Playgroud)


小智 8

 error:function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }
Run Code Online (Sandbox Code Playgroud)
在代码错误中ajax请求catch错误连接客户端到服务器如果你想在你的应用程序中显示错误消息发送成功范围

success: function(data){
   //   data is object  send  form server 
   //   property of data 
   //   status  type boolean 
   //   msg     type string
   //   result  type string
  if(data.status){ // true  not error 
         $('#api_text').val(data.result);
  }
  else 
  {
      $('#error_text').val(data.msg);
  }

}
Run Code Online (Sandbox Code Playgroud)


Guy*_*Guy 7

这可能是由于JSON字段名称没有引号.

从以下位置更改JSON结构:

{welcome:"Welcome"}
Run Code Online (Sandbox Code Playgroud)

至:

{"welcome":"Welcome"}
Run Code Online (Sandbox Code Playgroud)

  • 除非键是 JS 中的保留字,否则这应该不重要。我不认为这是这里的问题。 (2认同)

Nɪs*_*ʜ ॐ 7

此函数基本上生成唯一的随机 API 密钥,如果没有,则会出现带有错误消息的弹出对话框

在查看页面中:

<div class="form-group required">
    <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
    <div class="col-sm-6">
        <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
        <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
    </div>
</div>

<script>
$(document).ready(function(){
    $('.changeKey1').click(function(){
          debugger;
        $.ajax({
                url  :"index.php?route=account/apiaccess/regenerate",
                type :'POST',
                dataType: "json",
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                  var result =  data.sync_id.toUpperCase();
                        if(result){
                          $('#api_text').val(result);
                        }
                  debugger;
                  },
                error: function(xhr, ajaxOptions, thrownError) {
                  alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }

        });
    });
  });
</script>
Run Code Online (Sandbox Code Playgroud)

来自控制器:

public function regenerate(){
    $json = array();
    $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
    $json['sync_id'] = $api_key; 
    $json['message'] = 'Successfully API Generated';
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}
Run Code Online (Sandbox Code Playgroud)

可选的回调参数指定在 load() 方法完成时要运行的回调函数。回调函数可以有不同的参数:

类型:函数( jqXHR jqXHR, String textStatus, String errorThrown )

请求失败时调用的函数。该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象、描述发生的错误类型的字符串和可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“超时”、“错误”、“中止”和“解析器错误”。当发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。从 jQuery 1.5 开始,错误设置可以接受函数数组。每个函数都会被依次调用。注意:对于跨域脚本和跨域 JSONP 请求,不会调用此处理程序。


Vit*_*lva 5

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

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

我这样说是因为我在ASP.NET中遇到了类似的问题,我在这里抛出类似ArgumentException("不知道该做什么......"),但错误处理程序没有触发.

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


Nur*_*MAZ 5

jQuery.parseJSON对成功和错误很有用.

$.ajax({
    url: "controller/action",
    type: 'POST',
    success: function (data, textStatus, jqXHR) {
        var obj = jQuery.parseJSON(jqXHR.responseText);
        notify(data.toString());
        notify(textStatus.toString());
    },
    error: function (data, textStatus, jqXHR) { notify(textStatus); }
});
Run Code Online (Sandbox Code Playgroud)


Edi*_*ika 5

您在xhr对象中有一个抛出异常的JSON对象.只是用

alert(xhr.responseJSON.Message);
Run Code Online (Sandbox Code Playgroud)

JSON对象公开了另外两个属性:'ExceptionType'和'StackTrace'