Introduction to JavaScript error handling mechanism (with examples)
This article brings you an introduction to the JavaScript error handling mechanism (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Sometimes, in the tool function that you encapsulate, if no parameters are passed or parameters of the wrong type are passed in, some errors should be thrown as a warning; it will also be thrown if the framework is not used normally. If something goes wrong, if you don't know anything about the error, you won't be able to debug it. Based on the above, it is necessary to understand the error handling mechanism.
The following is the author's summary. If there are any errors, please point them out.Error constructor
There are a total of 8 error type constructors in the JavaScript specification
Error -- error object
SyntaxError --parsing process syntax error
TypeError --not valid Type
ReferenceError -- Invalid reference
RangeError -- The value exceeds the valid range
URIError -- Error in parsing URI encoding
EvalError -- Error in calling eval function
InternalError -- Javascript engine internal error Exception thrown, "Too much recursion"
Two of them are specially explained:
EvalError is an error in calling the eval function and has been deprecated. For backward compatibility, lower versions can still be used.
InternalError throws an error if the recursion is too deep. Most browsers have not implemented it. It is a non-standard method and is disabled in the production environment.
Inheritance relationship
Error is the base class of errors. Other types inherit the Error class and can be used. Object.getPrototypeOf() provided in ES6 to determine whether a class inherits another class.
console.log(Object.getPrototypeOf(SyntaxError) === Error); // true console.log(Object.getPrototypeOf(TypeError) === Error); // true console.log(Object.getPrototypeOf(RangeError) === Error); // true console.log(Object.getPrototypeOf(URIError) === Error); // true console.log(Object.getPrototypeOf(EvalError) === Error); // true console.log(Object.getPrototypeOf(ReferenceError) === Error); // true
Let’s talk about the use of each error type and the error scenarios.
Error
An error object can be created through the Error constructor. When a runtime error occurs, an Error instance object will be thrown.
Syntax: new Error([message])
Parameters:
message 可选,错误描述信息。
Throw an error
Use the throw statement to throw an exception
throw new Error('What is thrown here is Error message')
After running, it will be printed on the console:
Uncaught Error: The error message is thrown here
Note: After using throw to throw an exception, the subsequent code will no longer be executed.
Capturing errors
You can capture this error through the try{}catch(){} statement
try{ throw new Error('这里抛出的是错误信息') } catch(err){ alert(err.name + ' '+ err.message) }
Attribute description:
当使用new Error创建错误实例后,会有两个属性:
let e = new Error('What is thrown here is the error message');
name attribute is the type of error, this time it is Error
message attribute, which is the error message, this time it is 'thrown here' The error message is '
SyntaxError
Syntax error in the parsing process. There are many errors thrown by this type, which are often grammatical errors caused when writing, for example:
let n = 11; // Uncaught SyntaxError: Invalid or unexpected token let str = "hel"lo" // Uncaught SyntaxError: Unexpected identifier let 123Var = 'hi' // Uncaught SyntaxError: Invalid or unexpected token
There are many syntax errors, so I won’t list them one by one. When running in the browser, the console will throw an error and tell you which line it is, so it is more convenient for the debugger to use it. But you need to understand the error type as SyntaxError and the error message that follows, so that you can easily correct the error.
TypeError
is not a valid type. This kind of error means that the type given is not the required type, resulting in inoperability and a type error will be thrown.
The variable or parameter is not of the expected type,
The variable or parameter is not of the expected type
For example, new must be followed by a function, and the given one is not a function, a type error will be thrown
let fn = 'hello'; new fn;
Throws an error:
Uncaught TypeError: fn is not a constructor
Calling a method that does not exist on an object
let obj = {}; obj.fn()
Throws an error:
Uncaught TypeError: obj.fn is not a function
Of course, you can also force the incoming parameters to be specified types when encapsulating the function, otherwise a type error will be thrown.
function flatten(arr){ if( !Array.isArray(arr) ) { throw new TypeError('传入参数不是数组') } }
flatten('test');
When the incoming parameter is not an array, a custom type error is thrown:
Uncaught TypeError: The incoming parameter is not an array
ReferenceError
Invalid reference.
References a variable that does not exist
console.log(a);
Throws an error
Uncaught ReferenceError: a is not defined
Assign a variable to a data that cannot be assigned a value
This mistake is often made when making a judgment in the if statement after calling a method. The comparison operator == is written as the assignment operator =. For example, judging whether the first character of a string is the specified character:
let str = 'hello'; if( str.charAt(0) = 'h' ){ console.log('第一个字符为h'); }
Throws error:
Uncaught ReferenceError: Invalid left-hand side in assignment
RangeError
The value is outside the valid range. In some methods, the value passed in must be within a certain range, otherwise an out-of-range error will be thrown.
The length passed in when creating the array is less than 0
let arr = new Array(-1)
Throws an error:
Uncaught RangeError: Invalid array length
The repeat method repeats the specified string the number of times it is repeated is less than 0
let str = 'hello'; str.repeat(-1)
Throws error:
Uncaught RangeError: Invalid count value
URIError
Error in processing URI encoding. The function parameters are incorrect, mainly the six functions encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(), escape() and unescape().
For example:
decodeURIComponent('%'); decodeURI('%2')
Throws an error:
Uncaught URIError: URI malformed
Custom error type
Sometimes you want to customize the error type , you need to customize a constructor, and then let the prototype inherit Error.prototype.
function MyErrorType(message){ this.message = message || '错误'; this.name = 'MyErrorType'; this.stack = (new Error()).stack; // 错误位置和调用栈 } MyErrorType.prototype = Object.create(Error.prototype); MyErrorType.prototype.constructor = MyErrorType; throw new MyErrorType('自定义错误类型抛出错误')
关于调用的错误栈信息
提供的错误的跟踪功能,以什么样的调用顺序,在哪个文件的哪一行捕获到这个错误。
例如以下调用:
function trace() { try { throw new Error('myError'); } catch(e) { console.log(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg');
错误信息为:
Error: myError
at trace (
at b (
at a (
at
以上为抛错的构造函数的总结,如有误之处欢迎扶正。
The above is the detailed content of Introduction to JavaScript error handling mechanism (with examples). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
