如何捕獲所有未處理的 JavaScript 異常?


要捕獲所有未處理的 JavaScript 異常,請使用 window.error。onerror 事件處理程式提供三項資訊以標識確切的錯誤性質:

  • 錯誤訊息 - 瀏覽器將顯示的給定錯誤的相同訊息
  • URL - 發生錯誤的檔案
  • 行號 - 給定 URL 中導致錯誤的行號

示例

你可以嘗試執行以下程式碼來捕獲未處理的異常:

<html>
   <head>
      <script>
         <!--
            window.onerror = function (msg, url, line) {
               alert("Message : " + msg );
               alert("url : " + url );
               alert("Line number : " + line );
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>
      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>

更新於:23-Jun-2020

708瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.