javascript - ajax 错误回调中的重新抛出错误正在创建 Uncaught Error

标签 javascript jquery ajax

Error Image如何将 ajax 请求期间收到的错误消息冒泡到调用者?我在开发者工具的控制台中的抛出新错误(“某些错误”)处收到 Uncaught Error

我尝试了如下的简单示例,该示例会出现错误:

$("#myBtnAjax").click(function() {
  try {
    //Test();
    getMonthName("test");
  } catch (err) {
    alert("error " + err);
  }
});
function getMonthName(mo) {
  // Adjust month number for array index (1 = Jan, 12 = Dec)
  // var months = ['Jan', 'Feb','Mar','Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep','Oct', 'Nov', 'Dec'];
  mo = mo - 1;
  if (months[mo]) {
    return months[mo];
  } else {
    throw "InvalidMonthNo"; //throw keyword is used here
  }
}

$(document).ready(function() {
  $("#myBtnAjax").click(function() {
    try {
      Test();
    } catch (err) {
      alert("error " + err.message);
    }
  });

  function Test() {
    /**
     * http://api.jquery.com/jQuery.ajax/
     */
    $.ajax({
      url: "/non-existent-path-adsasd",

      type: "GET",

      dataType: "json",

      data: {
        name: "John",
        location: "Boston"
      },

      /**
       * A function to be called if the request fails.
       */
      error: function(jqXHR, textStatus, errorThrown) {
        alert(
          "An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!"
        );

        $("#result").html(
          "<p>status code: " +
            jqXHR.status +
            "</p><p>errorThrown: " +
            errorThrown +
            "</p><p>jqXHR.responseText:</p><div>" +
            jqXHR.responseText +
            "</div>"
        );
        console.log("jqXHR:");
        console.log(jqXHR);
        console.log("textStatus:");
        console.log(textStatus);
        console.log("errorThrown:");
        console.log(errorThrown);

        throw new Error("some error");
      },

      /**
       * A function to be called if the request succeeds.
       */
      success: function(data, textStatus, jqXHR) {
        $("#result").html(data);
        alert(
          "Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! "
        );
        console.log("jqXHR:");
        console.log(jqXHR);
        console.log("textStatus:");
        console.log(textStatus);
        console.log("data:");
        console.log(data);
      }
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>AJAX error handling with jQuery</h1>

<div>
    <button id="myBtnAjax">AJAX communication with error</button>
</div>

<div id="result">
</div>

最佳答案

尝试返回一个新的 Promise。 ajax 调用是异步的,因此抛出异常时 catch block 已经被传递。

$('#myBtnAjax').click(function() {
  Test()
    .then((data) => {
     //do something with response
    })
    .catch((err) => {
      alert(err); //handle error here
    });

});

function Test()
{
  return new Promise((resolve, reject) => {
    $.ajax({
      url: '/non-existent-path-adsasd',

      type: "GET",

      dataType: "json",

      data: {
        name: "John",
        location: "Boston"
      },

      /**
       * A function to be called if the request fails.
       */
      error: function(jqXHR, textStatus, errorThrown) {
        alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');

        $('#result').html('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
        console.log('jqXHR:');
        console.log(jqXHR);
        console.log('textStatus:');
        console.log(textStatus);
        console.log('errorThrown:');
        console.log(errorThrown);

        reject('Some Error');
      },

      /**
       * A function to be called if the request succeeds.
       */
      success: function(data, textStatus, jqXHR) {
        $('#result').html(data);
        alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
        console.log('jqXHR:');
        console.log(jqXHR);
        console.log('textStatus:');
        console.log(textStatus);
        console.log('data:');
        console.log(data);
        resolve(data);
      }
    });
  });
  /**
   * http://api.jquery.com/jQuery.ajax/
   */

}

关于javascript - ajax 错误回调中的重新抛出错误正在创建 Uncaught Error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775549/

相关文章:

javascript - BlobBuilder 和新的 Blob 构造函数有什么区别?

javascript - 使用 POST 从数据库中检索指定的项目

javascript - 从双重选择器中排除一个类的麻烦

javascript - jquery查找并替换url中的最后一个参数

javascript - RxJS 在 Ajax 错误后继续监听

c# - Ajax.BeginForm 未在 MVC 中使用 jQuery UI 对话框捕获 OnSuccess?

javascript - 从数组中设置 fullcalendar 中的事件

javascript - Turn.js 类似于 ionic 2 的翻页书

jquery - jQuery 可以通过选择器创建元素吗?

javascript - Ajax 安全