JavaScript - 擴充套件錯誤



在 JavaScript 中,**自定義**錯誤是指您自己建立的錯誤,而不是 JavaScript 丟擲的內建錯誤。您可以建立自定義錯誤來處理程式碼中可能發生的特定型別的錯誤。

要建立**自定義錯誤**,您可以使用 Error 建構函式。Error 建構函式以字串作為其引數,該字串將成為錯誤的訊息。

擴充套件 Error 類:建立自定義錯誤

建立自定義錯誤的最佳方法是建立一個新類並使用“extends”關鍵字擴充套件它。它使用了繼承的概念,並且自定義錯誤類繼承了 Error 類的屬性。

在 constructor() 函式中,您可以初始化自定義錯誤類的屬性。

語法

您可以按照以下語法透過擴充套件 Error 類來建立自定義錯誤。

class customError extends Error {
   constructor(message) {
      super(message)
      // Initialize properties
   }
}

在上面的程式碼中,我們使用 super() 方法呼叫父類建構函式。

您還可以在建構函式中初始化 customError 類的屬性。

示例

在下面的程式碼中,我們獲取使用者的輸入。當用戶點選“檢查年齡”按鈕時,它會呼叫 checkAge() 函式。

我們在 JavaScript 程式碼中定義了 ageError 類並使用 Error 類擴充套件它。在 ageError 類中,我們添加了 constructor() 函式來初始化屬性。

在 constructor() 函式中,我們使用 super() 方法初始化 Error 類的 message 屬性。此外,我們在建構函式中初始化了“name”和“age”屬性。

在 checkAge() 函式中,如果年齡小於 18,則丟擲錯誤,在 catch{} 塊中,我們列印錯誤訊息和年齡。

<html>
<body>
   <p>Enter your age: <input type = "number" id = "age" /> </p>
   <button onclick = "checkAge()"> Check Age </button>
   <p id = "demo"> </p>
   <script>
      const output = document.getElementById("demo");
      class ageError extends Error {
         constructor(message, age) {
            super(message);
            this.name = "ageError";
            this.age = age // Custom property
         }
      }
      function checkAge() {
         const ageValue = document.getElementById('age').value;
         try {
            if (ageValue < 18) { // Throw error when age is less than 18
               throw new ageError("You are too young", ageValue);
            } else {
               output.innerHTML = "You are old enough";
            }
         } catch (e) {
            output.innerHTML = "Error: " + e.message + ". <br>";
            output.innerHTML += "Age: " + e.age + "<br>";
         }
      }
   </script>
</body>
</html>

輸出

Enter your age: 5
Check Age
Error: You are too young.
Age: 5

如果您想為自定義錯誤建立多個新類,只是為了提供更清晰的錯誤型別和訊息,並且不想更改 Error 類的屬性,您可以使用以下語法。

class InputError extends Error {};

讓我們透過下面的示例學習它。

示例

在下面的程式碼中,我們建立了 3 個不同的自定義類並使用 Error 類擴充套件它們來建立自定義錯誤。

在 try{} 塊中,我們丟擲 StringError。

在 catch{} 塊中,我們使用 instanceOf 運算子檢查錯誤物件的型別並相應地列印錯誤訊息。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      class StringError extends Error { };
      class NumberError extends Error { };
      class BooleanError extends Error { };
      try {
         throw new StringError("This is a string error");
      } catch (e) {
         if (e instanceof StringError) {
            output.innerHTML = "String Error";
         } else if (e instanceof NumberError) {
            output.innerHTML = "Number Error";
         } else if (e instanceof BooleanError) {
            output.innerHTML = "Boolean Error";
         } else {
            output.innerHTML = "Unknown Error";
         }
      }
   </script>
</body>
</html>

輸出

String Error

多級繼承

您可以透過使用 Error 類擴充套件它來建立一個通用的自定義錯誤。之後,您可以擴充套件自定義錯誤類以建立一個更通用的錯誤類。

讓我們透過下面的示例瞭解它。

示例

在下面的程式碼中,我們定義了“NotFound”類並使用 Error 類擴充套件它。

之後,我們定義了“propertyNotFound”和“valueNotFound”類並使用“NotFound”類擴充套件它們。在這裡,我們進行了多級繼承。

在 try 塊中,如果陣列不包含 6,則丟擲 valueNotFound 錯誤。

在 catch 塊中,我們列印錯誤。

<html>
<body>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById("output");
      class NotFound extends Error {
         constructor(message) {
            super(message);
            this.name = "NotFound";
         }
      }
      
      // Further Inheritance
      class propertyNotFound extends NotFound {
         constructor(message) {
            super(message);
            this.name = "propertyNotFound";
         }
      }
      
      // Further Inheritance
      class ElementNotFound extends NotFound {
         constructor(message) {
            super(message);
            this.name = "ElementNotFound";
         }
      }

      try {
         let arr = [1, 2, 3, 4, 5];
         
         // Throw an error if array doesn't contain 6
         if (!arr.includes(6)) {
            throw new propertyNotFound("Array doesn't contain 6");
         }
      } catch (e) {
         output.innerHTML = e.name + ": " + e.message;
      }
   </script>
</body>
</html>

輸出

propertyNotFound: Array doesn't contain 6

如果任何物件不包含特定的屬性,您也可以丟擲 propertyNotFound 錯誤。

廣告