This chapter content
- Understand the errors reported by the browser
- Handling errors
- Debugging JavaScript code
Error handling
Error handling is important in programming. Any impactful Web application needs a well-developed error-handling mechanism.
Try-catch statement
Try {// code that may cause error} catch (e) {// What to do if an error occurs}Copy the code
Wrong type
There are several types of errors that can occur during code execution. Each error has a corresponding error type, and when an error occurs, an error object of the corresponding type is thrown. Ecma-262 defines the following seven error types:
-
Error
-
EvalError
-
RangeError
-
SyntaxError
-
ReferenceError
-
TypeError
-
URIError
-
An error of type RangeError is emitted when the value is outside the corresponding range:
try {
let items1 = new Array(-20);
var items2 = new Array(Number.MAX_VALUE);
} catch (e) {
console.dir(e)
}
Copy the code
- A ReferenceError occurs when the object is not found (in this case, it directly leads to what is known as an “object Expected” browser error). Typically, this error occurs when accessing a variable that does not exist:
try {
let obj = x;
} catch (e) {
console.dir(e)
}
Copy the code
- The SyntaxError type, which is caused when we pass a syntactically incorrect JavaScript string into an eval() function.
eval('a++ b')
Copy the code
- The TypeError type is often used in JavaScript when an unexpected type is stored in a variable, or when a nonexistent method is accessed. The reasons for this are varied. ** The most common case of a type error is when an argument passed to a function is not checked beforehand and the type passed does not match the expected type.
Function.prototype.toString.call('name') / / throwtypeError
Copy the code
- URIError is caused when encodeURI() or decodeURI() is used and the URI format is incorrect. This kind of error is rare, because the two functions described above are very fault-tolerant.
With different error types, you can learn more about the exception, which can help you handle the error appropriately.
try {
// ......
} catch (e) {
if(e instanceof TypeError) {// handle TypeError}else if(e instanceof ReferenceError) {// handle ReferenceError}else{// Handle other types of errors}}Copy the code
In cross-browser programming, checking error types is the easiest way to determine what to do; Error messages contained in the Message attribute vary by browser.
Use try-catch wisely
Try-catch is best for handling errors that are out of our control. Suppose you’re using a function in a large JavaScript library that can throw errors, intentionally or not. Since we can’t modify the library source code, we can put calls to this function in try-catch statements.
Throw an error
A try-catch statement is accompanied by a throw operator, which is used to throw custom errors at any time.
throw new Error('Something bad happend')
Copy the code
The above line throws a generic error with a custom error message. You can also use other error types as shown below, and you can simulate similar browser errors.
throw new SyntaxError('I dont like your syntax');
throw new TypeError('What type of variable do you take me for? ');
throw new RangeError('Sorry, you just dont have the range')
throw new EvalError('That doesnt evaluate.')
throw new URIError('Uri, is that you? ');
throw new ReferenceError('You didnt cite your references properly');
Copy the code
Error events
window.onerror = function(message, URL, line) {// Processing error}Copy the code
Policies for handling errors
slightly
Common error types
The core of error handling is to know what errors can occur in your code in the first place. Because JavaScript is loosely typed and does not validate function arguments, errors occur only during code execution. There are three types of errors to be concerned about:
- Type conversion error
- Data type error
- Communication error
Type conversion error
The congruence operator knows that it is comparing two different data types and simply returns false.
Data type error
Javascript is loosely typed, that is, variables and function parameters are not compared to ensure they are correctly typed before they are used.
Communication error
Any communication between Javascript and the server is likely to generate an error.
- The first communication error has to do with ill-formed urls or sent data. The most common problem is not using encodeURIComponent() to encode data before sending it to the server.
function addQueryString(url, name, value) {
if (url.indexOf('? ') === -1) {
url += '? ';
} else {
url += '&';
}
url += `&${encodeURIComponent(name)} = ${encodeURIComponent(value)}`;
return url;
}
Copy the code
Using this function, rather than building the URL manually, ensures correct encoding and avoids associated errors.
Distinguish between fatal and non-fatal errors
One of the most important parts of any error handling strategy is determining whether an error is fatal. Non-fatal errors can be determined based on one or more of the following conditions:
- Does not affect the user’s primary task
- Only a portion of the page is affected
- Can be restored
- Repeat the same operation to eliminate the error
Log errors to the server
A common practice in developing Web applications is to keep a centralized error log to find the cause of important errors.
To set up such a JavaScript error logging system, you first need to create a page on the server to process the error data. This page does nothing more than fetch data from query characters and then write the data to the error log. This page might use functions like the following:
function logError (lev, msg) {
letimg = new Image(); img.src = `log.php? e` }Copy the code
The logError() function takes two arguments: a numeric or string indicating severity and an error message. Image object is used to send the request, which is very flexible, mainly in the following aspects:
- Image objects are supported by all browsers, including those that do not support XMLHttpRequest objects.
- Cross-domain restrictions can be avoided.
- The probability of problems in recording errors is low. Most Ajax communication is handled by wrapper functions provided by JavaScript libraries, and if the library code itself has problems and you’re still relying on the library to log errors, it’s conceivable that error messages won’t get logged.
summary
Error handling is critical. Failure to anticipate errors and adopt recovery policies in advance may result in poor user experience.
Here are a few ways to prevent browsers from responding to JavaScript errors.
- Use try-catch statements where errors can occur, so you still have a chance to respond to errors in an appropriate way.
- Use the window.onerror event handler, which accepts all errors that a try-catch cannot handle.
In addition, any Web application should be analyzed for possible errors. The main reasons for errors in JavaScript are as follows.
- Type conversion
- Insufficient detection of data types
- There is an error in the data sent to or received from the server