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 错误。

广告
© . All rights reserved.