Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why give priority to errors in JavaScript

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you about why to give priority to dealing with errors in JavaScript, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Things don't always get what they want. When something goes wrong, we will be prompted by mistakes. Any developer should know the wrong concepts like the back of his hand, and the front-end developer must be familiar with the red text warning of errors in the browser console when the web application is running.

Error terms and exception handling mechanism terms are often used in programming, but they are often used interchangeably. The author believes that errors are thrown by the JavaScript engine and exception handling mechanisms are thrown by developers. But this may not happen in the Java programming language, where errors are unchecked and occur at run time, while exception handling mechanisms can occur at run time or compile time.

Error types in JavaScript

As a dynamically typed language, JavaScript does not warn of type errors before running. Although errors are usually attributed to Error objects in JavaScript, errors can be further classified. These branches inherit the characteristics of the Error object.

EvalError: represents the error thrown when using the global function eval ().

InternalError: represents an error thrown by the JavaScript engine due to an internal error. A typical example: "too many recursive methods" or something that is too large.

RangeError: indicates the error thrown when the value is out of range.

ReferenceError: indicates the error thrown when the referenced variable cannot be canceled. In other words, the referenced variable cannot be found or accessed.

SyntaxError: indicates an error thrown because the JavaScript engine was unable to interpret the given code because an invalid syntax was entered. Beginners often encounter such mistakes.

Type Error: usually indicates an error thrown because an operation instruction cannot be executed because an invalid data type is used in the operation.

URIError: indicates an error thrown by a function encodeURI () or decodeURI () that receives an invalid argument.

What is error handling?

Programs usually include two main types of problems, programmer errors and precision problems. A programmer's error means that a programmer does something stupid when writing code, such as forgetting to use the correct variable. The problem of accuracy is caused by objective factors, such as the failure of database connection due to slow network speed.

The first category of problems can be addressed by finding and repairing, but the second category of problems can only be fixed through preventive or proactive measures. This means considering the worst-case scenarios when writing code and dealing with them properly. This can be a general action performed when an error of any nature occurs, or it can be a specific action performed for a specific type of error. This defensive measure is called error handling.

Why deal with errors in the first place?

To understand why error handling is critical, let's imagine the following scenario: what happens if the error is not handled properly? Imagine that the application that has laid out the network does not place error handling. Many errors occur beyond the expectations of developers. For example, users try to upload malformed files if the situation is not dealt with in advance:

File upload failed

Users don't know why they failed (unless they can open the browser console to find out)

Users are likely not to visit the website in the future because of the above problems.

As a developer, there is no way to know why the program will stop running in this special case.

If appropriate error handling methods are adopted, many of the above problems will not arise. "appropriate" refers to the appropriate handling of the error when it occurs. Programmers deal with errors, but not "appropriately" them, which is one of the existing problems in network applications.

Whenever an error occurs, many websites usually display an error message. This is supposed to be the ultimate approach, but most inexperienced developers will adopt it first. The ideal way to deal with it is to deal with every mistake in an appropriate way, rather than curing the symptoms without getting to the root of the problem. In real situations, all possible scenarios may not be taken into account in a particular user experience.

But sometimes it may not be a good idea to tell users about special mistakes, because it's too complicated for the average user. In these cases, an error code can be provided to the user, and they will send the code to the customer service team, which can guide the appropriate user with reference to the error code.

Error handling is critical to error logging because errors cannot be logged if they are not processed first. The author believes that every developer needs to be proficient in error logging.

Methods of error handling

The error handling methods in JavaScript are listed below. Some are synchronous, others are asynchronous.

(1) try-catch

The try-catch method runs the code block statement and "catches" any errors thrown by the code block. If an error occurs while the code statement is running, the code execution flow stops and moves to the statement in the catch code block so that the errors can be handled appropriately. Try-catch code blocks can be used to handle both synchronous and asynchronous code.

Try {console.log (unknownVariable);} catch (error) {console.log (error); / / ReferenceError: unknownVariable isnot defined}

(2) Promise catch

The introduction of Promises makes JavaScript take on a new look. When Promise throws an error, we can use the catch method to handle the error. This is similar to the try-catch method, but there is no try code block in this method.

(3) Callback error

In traditional Node APIs, callback is used to handle responses and errors. Typically, the mode of callback is callback (err,res), where only "err" or "res" is a non-null value.

As shown above, if the asynchronous function fails, the err parameter will receive an error that should be handled appropriately.

(4) Error event

This is a common event handling pattern in NodeJS, where an error event is triggered when an error occurs.

Because port 80 is the default port for HTTP, the above code snippet cannot create the server, so an error is thrown.

(5) Onerror

The HTML element contains events, such as onclick, onchange, and so on. The onerror event is triggered when the DOM element throws an error. In addition, whenever a running error occurs in JavaScript, the window object triggers the onerror event.

_ window.onerror = function (message, source, lineno, colno, error) {/ / handle error}; element.error = function (event) {/ / handle element error)

Error boundary-React

The error boundary in React allows JavaScript's errors to be handled in a visual view structure without showing the corrupted UI to the user. You can create these React components simply by defining a new lifecycle method called componentDidCatch (error,info).

Error handling is an important part of programming, and you need to take it seriously if you want to build an efficient application.

This is why we give priority to dealing with errors in JavaScript. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report