如何捕捉所有未處理的 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>

更新時間: 2020-06-23

707 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.