首页 文章

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

提问于
浏览
657

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

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

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 .

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

20 回答

  • 326

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

    error: function (response) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
          alert("StackTrace: " + r.StackTrace);
          alert("ExceptionType: " + r.ExceptionType);
    }
    
  • 94

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

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

    首先,我们需要在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

  • 0

    使用以下命令在服务器上抛出新异常:

    Response.StatusCode = 500

    Response.StatusDescription = ex.Message()

    我相信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
    
  • 3

    一般/可重用的解决方案

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

    在服务器上验证失败时抛出

    • Custom exception ModelStateException (当我们使用数据注释并使用强类型控制器操作参数时,模型状态报告验证错误)

    • Custom controller action error filter 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
        }
    });
    

    服务器端代码

    [HandleModelStateException]
    public ActionResult Create(User user)
    {
        if (!this.ModelState.IsValid)
        {
            throw new ModelStateException(this.ModelState);
        }
    
        // create new user because validation was successful
    }
    

    整个问题在this blog post中有详细说明,您可以在其中找到在您的应用程序中运行此代码的所有代码 .

  • 34

    如果有人在2016年作为答案,请使用 .fail() 进行错误处理,因为从jQuery 3.0开始不推荐使用 .error()

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

    我希望它有所帮助

  • 75
    error:function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
          }
    

    在代码错误中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);
      }
    
    }
    
  • 2

    这就是我所做的,它在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"};
    }
    

    在客户端,这就是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;
        }
    });
    
  • 4

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

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

    从以下位置更改JSON结构:

    {welcome:"Welcome"}
    

    至:

    {"welcome":"Welcome"}
    
  • 5
    $("#save").click(function(){
        $("#save").ajaxError(function(event,xhr,settings,error){
            $(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
        });
    });
    
  • 7

    此函数基本上生成唯一的随机API密钥's and in case if it doesn' t然后弹出对话框,出现错误信息

    In View Page:

    <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>
    

    From Controller:

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

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

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

    请求失败时要调用的函数 . 该函数接收三个参数:jqXHR(在jQuery 1.4.x中,XMLHttpRequest)对象,描述发生的错误类型的字符串和可选的异常对象(如果发生) . 第二个参数的可能值(除了null)是"timeout","error","abort"和"parsererror" . 当发生HTTP错误时,errorThrown会收到HTTP状态的文本部分,例如"Not Found"或"Internal Server Error."从jQuery 1.5开始,错误设置可以接受一系列函数 . 每个函数将依次调用 . 注意:不会为跨域脚本和跨域JSONP请求调用此处理程序 .

  • 5

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

    xhr.responseText
    

    ..在你的JavaScript中 .

  • 14

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

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

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

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

  • 16

    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

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

    $("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);
                     });
    
  • 14

    虽然问这个问题已经很多年了,但我仍然没有找到 xhr.responseText 作为我正在寻找的答案 . 它以下列格式返回给我:

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

    我绝对不想向用户展示 . 我正在寻找的是如下所示:

    alert(xhr.responseJSON.message);
    

    xhr.responseJSON.message 给了我来自Json对象的确切消息,可以向用户显示 .

  • 0

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

    我自己并没有编写所有的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) ); 
    })
    
  • 4
    $("#fmlogin").submit(function(){
       $("#fmlogin").ajaxError(function(event,xhr,settings,error){
           $("#loading").fadeOut('fast');       
           $("#showdata").fadeIn('slow');   
           $("#showdata").html('Error please, try again later or reload the Page. Reason: ' + xhr.status);
           setTimeout(function() {$("#showdata").fadeOut({"opacity":"0"})} , 5500 + 1000); // delays 1 sec after the previous one
        });
    });
    

    如果有任何表格提交验证

    只需使用其余的代码

    $("#fmlogin").validate({...
    

    ... ... });

  • 4

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

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

    alert(xhr.responseJSON.Message);
    

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

相关问题