Javascript 简明教程

JavaScript - Custom Errors

Custom errors 是在 JavaScript 中创建用户定义错误类型的一种方法。这对于处理特定类型的错误(例如,数据库错误或 HTTP 错误)很有用。

Custom errors are a way to create user-defined error types in JavaScript. This can be useful for handling specific types of errors, such as database errors or HTTP errors.

JavaScript 包含多个用于错误的内置对象。只要在 JavaScript 代码中发生任何错误,它就会抛出 Error 类的实例。不过,你也可以使用“throw”语句通过自定义消息来抛出 Error 类的实例。

JavaScript contains multiple built-in objects for the errors. Whenever any error occurs in the JavaScript code, it throws an instance of the Error class. However, you can also throw the instance of the Error class with a custom message using the 'throw' statement.

在某些情况下,开发人员需要创建自定义错误。例如,您在输入中获取用户的年龄。如果用户的年龄未满 18 岁,您可以抛出自定义错误,如“ageNotValid”,以获得更明确的信息。

In some conditions, developers need to create custom errors. For example, you are taking the user’s age in the input. If the user’s age is not above 18, you can throw a custom error like 'ageNotValid' for more clarification.

首先让我们了解错误类的语法,然后您将学习如何创建自定义错误。

Let’s understand the syntax of the Error class first, and then you will learn to create custom errors.

The Error Class

在 JavaScript 中,错误是一个通用错误类。您可以创建错误类的一个实例,并将自定义消息作为参数传递。

In JavaScript, Error is a generic class for the errors. You can create an instance of the Error class and pass the custom message as an argument.

Error 类包含三个属性:name、message 和 stack。

The Error class contains three properties: name, message, and stack.

因此,你可以假设 Error 类的语法如下所示。

So, you can assume the syntax of the Error class as shown below.

class Error {
   constructor(message) {
      this.message = message;
      this.name = "Error";
      this.stack = <call stack>;
   }
}

上述语法中的“stack”属性是非标准属性。它仅受 Firefox 浏览器支持。

The 'stack' property is a non-standard property in the above syntax. It is supported by the Firefox browser only.

Creating Custom Errors Using the Instance of the Error Class

创建自定义错误的最简单的方法是创建 Error 类的实例并更改其属性。

The easiest way to create a custom error is to create an instance of the Error class and change its properties.

Syntax

你可以按照以下语法通过更改 Error 类的实例属性来创建自定义错误。

You can follow the syntax below to create custom errors by changing the properties of the instance Error class.

const customError = new Error(message);
customError.name = "CustomError";

此处,我们创建了“Error”类实例并传递了“message”作为参数。此外,我们更改了“name”属性的值。同样,如果你不想将“message”属性作为 Error() 构造函数的参数传递,则可以更改“message”属性的值。

Here, we have created the 'Error' class instance and passed the 'message' as an argument. Also, we have changed the value of the 'name' property. Similarly, you can change the value of the 'message' property if you don’t want to pass it as an Error() constructor argument.

Parameter

  1. message − It is a text message to represent the error.

Example

在下面的代码中,我们创建了 Error 类的实例并将其存储在“customError”变量中。之后,我们将“name”属性的值更改为“CustomError”。

In the code below, we have created the instance of the Error class and stored it in the 'customError' variable. After that, we changed the value of the 'name' property to the 'CustomError'.

在 try{} 块中,我们使用了“throw”语句来抛出自定义错误,而在 catch{} 块中,我们打印错误名称和消息。

In the try{} block, we have used the 'throw' statement to throw the custom error, and in the catch{} block, we print the error name and message.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const customError = new Error("This is a custom error");
      customError.name = "CustomError";
      try {
         throw customError;
      } catch (err) {
         document.getElementById("output").innerHTML = err;
      }
   </script>
</body>
</html>
CustomError: This is a custom error

Creating the Custom Errors Using the Function Constructor

你可以使用函数构造函数来创建对象的模板。函数构造函数应包含“name”和“message”属性。

You can use the function constructor to create the template for the object. The function constructor should contain the 'name' and 'message' properties.

接下来,你可以使用 Error 类的原型来更改函数构造函数的原型。

Next, you can change the prototype of the function constructor with the prototype of the Error class.

Syntax

你可以按照以下语法使用函数类的构造函数创建自定义错误。

You can follow the syntax below to create custom errors using the constructor of the function class.

function validationError(messag, name) {
   this.message = messag;
   this.name = name;
}
validationError.prototype = Error.prototype;

在上述语法中,我们定义了 validationError() 函数,将 message 和 name 作为参数。之后,我们使用参数值初始化函数的 message 和 name 属性。

In the above syntax, we have defined the validationError() function, taking the message and name as a parameter. After that, we initialize the message and name properties of the function with parametric values.

接下来,我们使用 Error 类的原型来更改函数的原型。

Next, we change the prototype of the function with the prototype of the Error class.

Example

在下面的代码中,我们定义了 validationError() 函数构造函数,并使用 Error 类的原型继承了它。

In the code below, we have defined the validationError() function constructor and inherited it using the prototype of the Error class.

在 try{} 块中,我们定义了“str”变量并用数值对其进行初始化。之后,我们使用 typeof 运算符验证“str”变量的类型。如果它不是字符串,我们会传递 message 和 name 作为参数来抛出“validationError”。

In the try{} block, we have defined the 'str' variable and initialized it with the numeric value. After that, we validate the type of the 'str' variable using the typeof operator. If it is not a string, we throw 'validationError' by passing the message and name as an argument.

在 catch{} 块中,我们在网页上打印消息。你可以运行代码,并观察输出中的错误。

In the catch{} block, we print the message on the web page. You can run the code, and observe the error in the output.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      function validationError(message = "", name = "validationError") {
         this.message = message;
         this.name = name;
      }
      validationError.prototype = Error.prototype;

      try {
         let str = 10;
         if (typeof str != "string") {
            throw new validationError("Not a string", "NotStringError");
         } else {
            output.innerHTML = "String is valid";
         }
      } catch (e) {
         output.innerHTML = e.name + ": " + e.message;
      }
   </script>
</body>
</html>
NotStringError: Not a string

Creating Custom Errors by Extending the Error Class

创建自定义错误的最佳方法是创建一个新类并使用“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.

你可以使用上面的任意方法来创建满足你的需求的自定义错误。

You can use any of the above approaches to create custom errors according to your requirements.