In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you what the JavaScript error handling process is like, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
What are errors in programming?
Our development process is not always plain sailing. Especially in some cases, we may want to stop the program or notify the user when something bad happens.
In cases like these, we can write our own custom errors to manage, or just let the engine define these errors for us. Once we have the error definition, we can notify the user with a message or stop the execution of the program.
What is the error in JavaScript
The error in JavaScript is an object. To create an error in JS, you can use the Error object, as follows:
Const err = new Error ('Hoho, something seems to be wrong!')
You can also omit the new keyword:
Const err = Error ('Hoho, something seems to be wrong!')
Created, the error object has three properties:
Message: a string with an error message
Name: type of error
Stack: stack trace of function execution
For example, we use the TypeError object to create an error, the corresponding message is the incoming word symbol created, and name is "TypeError"
Const wrongType = TypeError ("Hoho, something seems to be wrong!") WrongType.message / / "Huo Huo, something seems to be wrong!" WrongType.name / / "TypeError"
Many types of errors in JavaScript
There are many types of errors in JavaScript, such as:
Error
EvalError
InternalError
RangeError
ReferenceError
SyntaxError
TypeError
URIError
Remember that all of these error types are actual constructors, which means that a new error object is returned.
In our code, we mainly use the two most common types, Error and TypeError, to create our own error objects.
Most of the time, most of the errors will come directly from JavaScript engines, such as InternalError or SyntaxError.
If you reassign to a variable declared by const, a TypeError error will be raised.
Const name = "front-end wisdom" name = "Wang Daye" / TypeError: Assignment to constant variable.
A SyntaxError error is usually a mistyped keyword, as shown below:
Va x ='33 hours; / / SyntaxError: Unexpected identifier
Or, when using keywords in the wrong place, such as the use of await and async:
Function wrong () {await 99;} wrong (); / / SyntaxError: await is only valid in async function
Another example of TypeError is a DOM element that does not exist on the page.
Uncaught TypeError: button is null
In addition to these built-in errors, there are also in browsers:
DOMException
DOMError, which is now abandoned, is no longer in use.
DOMException is a series of errors related to Web API. When we perform stupid operations in the browser, they are thrown, such as:
Document.body.appendChild (document.cloneNode (true))
Results:
Uncaught DOMException: Node.appendChild: May not add a Document as a child
What is an anomaly?
Most developers think that errors and exceptions are the same thing. In fact, the error object becomes an exception only when it is thrown.
To throw an exception in JavaScript, we use the throw keyword to throw the error:
Const wrongType = TypeError ("Hoho, something seems to be wrong!") Throw wrongType
Abbreviated form:
Throw TypeError ("Huo Huo, something seems to be wrong!")
Or
Throw new TypeError ("Huo Huo, something seems to be wrong!")
It is unlikely that an async is thrown outside the function body or condition, consider the following example:
Function toUppercase (string) {if (typeof string! = = "string") {throw TypeError ("Huo Huo, something seems to be wrong!") ;} return string.toUpperCase ();}
Here we check whether the function argument is a string. If not, we throw an exception. Technically, anything can be thrown in JavaScript, not just the wrong object
Throw Symbol (); throw 33; throw "Error!"; throw null
However, it's best to avoid these things: always throw the right wrong object, rather than some basic type.
This contributes to the consistency of error handling in the code. Other members can expect to access error.message or error.stack on the error object to know the source of the error.
What happens when we throw an exception?
An exception is like a rising elevator: once you throw one, it bubbles in the program stack unless it is caught somewhere.
Consider the following code:
Function toUppercase (string) {if (typeof string! = = "string") {throw TypeError ("Parameter type needs to be string");} return string.toUpperCase ();} toUppercase (4)
When you run the code, you will see on the console:
Uncaught TypeError: Wrong type given, expected a string toUppercase http://localhost:5000/index.js:3 http://localhost:5000/index.js:9
You can see the exact line on which the error occurred.
This report is a stack trace that helps track problems in the code. Stack trace from bottom to top:
ToUppercase http://localhost:5000/index.js:3 http://localhost:5000/index.js:9
In addition to seeing this stack trace in the browser's console, you can also view it through the stack property of the error object.
If the exception is not caught, that is, the programmer does nothing to catch it, the program will crash.
When and where to catch exceptions in the code depends on the specific use case.
For example, we might want to pass an exception in the stack so that the program crashes completely. This happens when it is safer to make an error stop program than to deal with invalid data.
Next, let's take a look at error and exception handling in JavaScript synchronization and async.
Error handling in synchronization
The synchronization code is simple in most cases, so its error handling is also simple.
Error handling of conventional functions
The synchronization code is executed in the same order as the write order. Let's look at the previous example again:
Function toUppercase (string) {if (typeof string! = = "string") {throw TypeError ("Parameter type needs to be string");} return string.toUpperCase ();} toUppercase (4)
Here, the engine invokes and executes toUppercase. All this happens at the same time. To catch the exception thrown by the synchronization function, we can use try/catch/finally:
Try {toUppercase (4);} catch (error) {console.error (error.message);} finally {}
Try/catch/finally is a synchronous structure, but it can also catch exceptions that occur asynchronously.
Use the generator function to handle errors
The generator function in JavaScript is a special function. In addition to providing a two-way communication channel between its internal scope and users, it can also be paused and resumed at will.
To create a generator function, we put a * after the function keyword:
Function* generate () {/ /}
You can use yield to return a value within a function:
Function* generate () {yield 33; yield 99;}
The return value of the generator function is an iterator object (iterator object). To extract values from the generator, we can use two methods:
Use the next () method
Traversing through for...of
To get the value in the generator, as shown below, we can do this:
Function* generate () {yield 33; yield 99;} const go = generate (); const firstStep = go.next (). Value; / / 33 const secondStep = go.next (). Value; / / 99
Builders can also work in other ways: they can receive values and exceptions returned by the caller.
In addition to next (), the iterator object returned from the generator also has a throw () method. Using this method, we can stop the program by injecting an exception into the generator:
Function* generate () {yield 33; yield 99;} const go = generate (); const firstStep = go.next (). Value; / / 33 go.throw (Error ("I want to end you!"); const secondStep = go.next (). Value; / / an exception will be thrown here
To get this error, you can use try/catch/finally in the generator function:
Function* generate () {try {yield 33; yield 99;} catch (error) {console.error (error.message);}}
The following example uses for...of to get the value in the generator function:
Function* generate () {yield 33; yield 99; throw Error ("I want to end you!")} try {for (const value of generate ()) {console.log (value)}} catch (error) {console.log (error.message)} / * output: 3399 I want to end you! * /
Error handling in Asynchronous
JavaScript is synchronous in nature and is a single-threaded language.
Hosting environments such as browser engines use a lot of Web API, which enhances JS to interact with external systems and handle operations bound to Imando.
Asynchronous operations in browsers include timer-related functions, events, and Promise.
Error handling in asynchrony is different from synchronous error handling. Let's look at some examples.
Error handling of timer
Consider the following code snippet:
Function failAfterOneSecond () {setTimeout (() = > {throw Error ("Something went wrong!");}, 1000);}
This function throws an exception in about 1 second. What is the correct way to handle this exception?
The following methods do not work:
Function failAfterOneSecond () {setTimeout (()) = > {throw Error ("Something went wrong!");}, 1000);} try {failAfterOneSecond ();} catch (error) {console.error (error.message);}
We know that try/catch is synchronous and setTimeout is asynchronous. By the time the setTimeout callback is executed, the try/catch is already finished, so the exception cannot be caught.
They are on two different tracks:
Track A:-- > try/catch Track B:-- > setTimeout-- > callback-- > throw
If you can get the program running, move try/catch to setTimeout. But this doesn't make much sense, and we'll use Promise to solve this kind of problem later.
Error handling in event
The event actions (listening and triggering) of DOM are defined in the EventTarget interface. The Element node, the document node, and the window object all deploy this interface. In addition, this interface is also deployed with built-in objects in browsers such as XMLHttpRequest, AudioNode, AudioContext, etc. This interface is three methods, addEventListener and removeEventListener are used to bind and remove listener functions, and dispatchEvent is used to trigger events.
The error handling mechanism for DOM events follows the same scheme as any asynchronous Web API.
Consider the following example:
Const button = document.querySelector ("button"); button.addEventListener ("click", function () {throw Error ("Can't touch this button!");})
Here, an exception is thrown immediately after clicking the button. How do we catch it? The following methods don't work and won't stop the program from crashing:
Const button = document.querySelector ("button"); try {button.addEventListener ("click", function () {throw Error ("Can't touch this button!");});} catch (error) {console.error (error.message);}
Like setTimeout, addEventListener is executed asynchronously.
Track A:-- > try/catch Track B:-- > addEventListener-- > callback-- > throw
If you can get the program running, move try/catch to addEventListener. But this doesn't make much sense, and we'll use Promise to solve this kind of problem later.
How's onerror?
The HTML element has many event handlers, such as onclick,onmouseenter,onchange, and, of course, onerror.
The onerror event handler triggers when the img tag or the script tag encounters a resource that does not exist.
Consider the following example:
...
...
When the file does not exist, the console reports the following error:
GET http://localhost:5000/nowhere-to-be-found.png [HTTP/1.1 404 Not Found 3ms]
In JS, we can catch this error through onerror:
Const image = document.querySelector ("img"); image.onerror = function (event) {console.log (event);}
A better way:
Const image = document.querySelector ("img"); image.addEventListener ("error", function (event) {console.log (event);})
This approach is useful in some cases where requested resources are lost, but onerror has nothing to do with throw and try/cathc.
The above is what the JavaScript error handling process is like. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.