Errors in JavaScript: Why are these errors prioritized?

The full text is 2767 words and the expected learning time is 7 minutes

 

Errors in JavaScript: Why are these errors prioritized?

Source: unsplash

The development of things is not always what you want. When something goes wrong, we will be notified via errors. Any developer should be well aware of the concept of errors. Front-end developers must be familiar with the red text warning in the browser console to notify errors when the web application is running.

 

Error terms and exception handling mechanism terms are not uncommon in programming, but they are often used interchangeably. The author believes that errors are thrown by the JavaScript engine, and the exception handling mechanism is thrown by the developer. But this situation may not appear in the Java programming language. In Java, errors are of unchecked type and appear at runtime; and the exception handling mechanism can appear at runtime or compile time.

 

Types of errors in JavaScript

 

As a dynamically typed language, JavaScript will not warn about type errors before running. Although errors usually belong to the Error object 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: indicates an error thrown by the JavaScript engine due to an internal error. A typical example: "Too many recursive methods" or something is too big.

 

· RangeError: indicates the error thrown when the value exceeds the range.

 

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

 

· SyntaxError: Indicates an error thrown by the JavaScript engine unable to interpret the given code due to invalid syntax. Novices often encounter such errors.

 

· Type Error: usually indicates an error that is thrown because an invalid data type is used in the operation, which makes the operation instruction impossible to execute.

 

· URIError: indicates the error thrown by the function encodeURI() or decodeURI() receiving invalid parameters.

 

What is error handling?

 

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

 

The first type of problems can be dealt with by finding and repairing, but the second type of problems can only be fixed through preventive measures or proactive measures. This means taking into account the worst possible possibilities when writing code and handling them properly. This can be a normal operation performed when an error of any nature occurs, or a specific operation performed for a specific type of error. This defensive measure is called error handling.

 

Why handle errors in the first place?

 

In order to understand why error handling is so important, let's imagine the following scenario: What will happen if the error is not handled properly? Suppose that the networked application does not have error handling. There are many errors that occur beyond the developers’ expectations. Take the user’s attempt to upload a file with the wrong format as an example. If this situation is not handled in advance:

 

· File upload failed

· The user has no way of knowing why it failed (unless they can open the browser console to find out)

· Users are likely to not visit the website in the future due to the above problems

· As a developer, there is no way to know why the program will stop running under this special situation

 

If appropriate error handling methods are used, many of the above problems will not occur. "Appropriate" refers to the appropriate handling method when an error occurs. The programmer handled the error, but did not handle the error "appropriately", which is one of the existing problems of network applications.

 

Whenever an error occurs, many websites usually display an error message. This should be the ultimate solution, but most inexperienced developers will use this method first. The ideal treatment method is to deal with every error with a suitable treatment method, rather than treating the symptoms and not the root cause. In actual situations, all possible situations may not be considered in a particular user experience.

 

But sometimes, it may not be a good idea to inform users of particular errors, because it is too complicated for ordinary users. In these cases, a wrong code can be provided to the user, and they will send the code to the customer service team, which can guide the corresponding user by referring to the error code.

 

Error handling is critical to error logging, because if you don't handle the error first, you cannot log the error. The author believes that every developer needs to be proficient in error logging.

 

Error handling method

 

The following lists the error handling methods in JavaScript. Some are synchronous, others are asynchronous.

 

· try-catch

 

The try-catch method runs the code block statement and "catch" any errors thrown by the code block. If an error occurs during the execution of the code statement, the code execution flow will stop and move to the statement in the catch code block, so that these errors can be handled appropriately. The try-catch code block can be used to handle synchronous and asynchronous code.

 

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

 

· Promise catch

 

The introduction of Promises has given JavaScript a new look. When a 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 block in this method.

Errors in JavaScript: Why are these errors prioritized?

 

· Callback error

 

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

Errors in JavaScript: Why are these errors prioritized?

 

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

 

· Error event

 

This is a common event handling mode in NodeJS, and an error event will be triggered when an error occurs.

Errors in JavaScript: Why are these errors prioritized?

 

Since port 80 is the default port of HTTP, the above code snippet cannot create a server, so an error will be thrown.

 

· Onerror

 

HTML elements contain some events, such as onclick, onchange, etc. When the DOM element throws an error, the onerror event will be triggered. In addition, whenever a JavaScript runtime error occurs, the window object will trigger the onerror event.

 

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

 

Error boundary — React

 

Error boundaries in React allow JavaScript errors to be handled in the intuitive view structure without showing the user a broken UI. Just define a new lifecycle method called componentDidCatch(error,info) to create these React components.

 

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

Errors in JavaScript: Why are these errors prioritized?

Share the dry goods of AI learning and development together

Welcome to follow the full platform AI vertical self-media "core reading"

(Add the editor WeChat: dxsxbb, join the reader circle, and discuss the freshest artificial intelligence technology together~)

Guess you like

Origin blog.csdn.net/duxinshuxiaobian/article/details/112634515