Javascript 简明教程
JavaScript - Extending Errors
JavaScript 中的 custom 错误是你自己创建的错误,与 JavaScript 抛出的内置错误相反。你可以创建自定义错误来处理代码中可能出现的特定类型的错误。
The custom errors in JavaScript are errors that you create yourself, as opposed to the built-in errors that JavaScript throws. You can create custom errors to handle specific types of errors that may occur in your code.
要创建 custom error ,可以使用 Error 构造函数。Error 构造函数采用一个字符串作为其参数,该字符串将成为错误消息。
To create a custom error, you can use the Error constructor. The Error constructor takes a string as its argument, which will be the message of the error.
Extending the Error Class: Creating Custom Errors
创建自定义错误的最佳方法是创建一个新类并使用“extends”关键字进行扩展。它使用了继承的概念,并且自定义错误类继承了 Error 类的属性。
The best way to create custom errors is by creating a new class and extending it using the 'extends' keyword. It uses the concept of inheritance, and the custom error class inherits the properties of the Error class.
在 constructor() 函数中,你可以初始化自定义错误类的属性。
In the constructor() function, you can initialize the properties of the custom error class.
Syntax
你可以按照下面的语法通过扩展 Error 类来创建自定义错误。
You can follow the syntax below to create custom errors by extending the Error class.
class customError extends Error {
constructor(message) {
super(message)
// Initialize properties
}
}
在上面的代码中,我们使用 super() 方法调用父类构造函数。
In the above code, we call the parent class constructor using the super() method.
你也可以在构造函数中初始化 customError 类的属性。
You can also initialize the properties of the customError class in the constructor function.
Example
在下面的代码中,我们从用户处获取输入。当用户单击检查年龄按钮时,它会调用 checkAge() 函数。
In the code below, we take the input from the user. When a user clicks the check age button, it calls the checkAge() function.
我们在 JavaScript 代码中定义了 ageError 类,并使用 Error 类对其进行了扩展。在 ageError 类中,我们添加了 constructor() 函数来初始化属性。
We have defined the ageError class in JavaScript code and extended it with the Error class. In the ageError class, we have added the constructor() function to initialize the properties.
在 constructor() 函数中,我们使用 super() 方法来初始化 Error 类的 message 属性。此外,我们还在构造函数中初始化了“name”和“age”属性。
In the constructor() function, we used the super() method to initialize the message property of the Error class. Also, we have initialized the 'name' and 'age' properties in the constructor function.
在 checkAge() 函数中,如果年龄小于 18 岁,则抛出错误,在 catch{} 块中,我们打印错误消息和年龄。
In the checkAge() function, we throw the error if the age is less than 18, and in the catch{} block, we print the error message and age.
<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>
Output
Enter your age: 5
Check Age
Error: You are too young.
Age: 5
如果你想为自定义错误创建多个新类,只是为了提供明确的错误类型和消息,而不想要改变 Error 类的属性,可以使用以下语法。
If you want to create multiple new classes for the custom errors only to provide the clarified error type and message and don’t want to change the properties of the Error class, you can use the syntax below.
class InputError extends Error {};
让我们通过下面的示例学习它。
Let’s learn it via the example below.
Example
在下面的代码中,我们创建了 3 个不同的自定义类,并使用 Error 类对其进行了扩展,以创建自定义错误。
In the code below, we have created 3 different custom classes and extended them with the Error class to create custom errors.
在 try{} 块中,我们抛出 StringError。
In the try{} block, we throw the StringError.
在 catch{} 块中,我们使用 instanceOf 运算符来检查错误对象的类型,并相应地打印错误消息。
In the catch{} block, we used the instanceOf operator to check the type of the error object and print the error message accordingly.
<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>
Multilevel Inheritance
你可以通过继承 Error 类来创建一个通用的自定义错误。之后,你可以扩展自定义错误类来创建一个更通用的错误类。
You can create a general custom error by extending it with the Error class. After that, you can extend the custom error class to create a more generalized error class.
让我们通过以下示例了解它。
Let’s understand it via the example below.
Example
在下面的代码中,我们定义了 'NotFound' 类,并使用 Error 类扩展它。
In the code below, we have defined the 'NotFound' class and extended it using the Error class.
之后,我们定义了 'propertyNotFound' 和 'valueNotFound' 类,并使用 'NotFound' 类扩展它们。在这里,我们执行了多重继承。
After that, we defined the 'propertyNotFound' and 'valueNotFound' classes and extended them with the 'NotFound' class. Here, we have done the multilevel inheritance.
在 try 块中,如果数组不包含 6,我们抛出 valueNotFound 错误。
In the try block, we throw a valueNotFound error if the array doesn’t contain 6.
在 catch 块中,我们打印错误。
In the catch block, we print the error.
<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>