Front.
Error handling is critical for Web application development, not anticipating possible errors in advance, not taking a recovery strategy in advance, and potentially leading to a poor user experience. Because any JavaScript error can cause a Web page to become unusable, as a developer, you must know when it can go wrong, why it goes wrong, and what is amiss. This article will describe in detail the error handling mechanism in JavaScript
Error Object
An Error object is an object that contains an error message and is the native object of JavaScript. When the code parsing or run-time error occurs, the JavaScript engine automatically generates and throws an instance of an Error object, and the entire program is interrupted where the error occurred
Console.log (t);//uncaught referenceerror:t is not defined
ECMA-262 stipulates that the Error object includes two attributes: Message and name. The message property holds error messages, and the Name property saves the error type
Copy Code code as follows:
In general, use the Try-catch statement to catch errors
try{
T
}catch (ex) {
Console.log (ex.message);//t is not defined
Console.log (ex.name);//referenceerror
}
The browser also extends the properties of the Error object, adding other relevant information. The most common browser vendors implement the Stack property, which represents stack trace information (Safari does not support)
Copy Code code as follows:
try{
T
}catch (ex) {
Console.log (ex.stack);//@file:///d:/wamp/www/form.html:12:2
}
Of course, you can use the error () constructor to create the wrong object. If the message parameter is specified, the Error object is used as its message property, and if not specified, it uses a predefined default string as the value of the property
Copy Code code as follows:
New Error ();
New Error (message);
In general, use the throw statement to throw an error
throw new Error (' Test ');//uncaught error:test
throw new error ();//uncaught error
Copy Code code as follows:
function Usererror (message) {
this.message = message;
THIS.name = "Usererror";
}
Usererror.prototype = new Error ();
UserError.prototype.constructor = Usererror;
throw new Usererror ("errormessage");//uncaught usererror:errormessage
When the error () constructor is invoked directly as a function without using the new operator, its behavior is the same as when it is invoked with the new operator
Copy Code code as follows:
Error ();
Error (message);
Throw Error (' test ');//uncaught error:test
Throw error ();//uncaught error
The Error object has a ToString () method that returns the message property of the ' ERROR: ' + Error Object
Copy Code code as follows:
var test = new Error (' Testerror ');
Console.log (Test.tostring ());//' Error:testerror '
Error type
There are several types of errors that may occur during code execution. Each error has a corresponding type of error, and when the error occurs, the appropriate type of error object is thrown. ECMA-262 defines the following 7 types of errors:
Copy Code code as follows:
Error
Evalerror (eval error)
Rangeerror (range error)
Referenceerror (reference error)
SyntaxError (Syntax error)
TypeError (type error)
Urierror (URI error)
Where error is the base type and other error types inherit from that type. Therefore, all error types share a set of identical properties. Error type errors are rarely seen if they are also thrown by browsers; The primary purpose of this base type is for developers to throw custom errors
"Evalerror (eval error)"
When the Eval function is not executed correctly, a Evalerror error is thrown. The error type is no longer present in the ES5, but is persisted only to ensure compatibility with the previous code
"Rangeerror (range error)"
Errors of type Rangeerror trigger when a value is out of range, including the range beyond the array length and the number of values beyond the range.
Copy Code code as follows:
New Array ( -1);//uncaught rangeerror:invalid Array length
New Array (number.max_value);//uncaught rangeerror:invalid Array length
(1234). toexponential;//uncaught rangeerror:toexponential () argument must be between 0 and 20
(1234). toexponential ( -1);////uncaught rangeerror:toexponential () argument must be between 0 and 20
"Referenceerror (reference error)"
Referenceerror (reference error) is triggered when referencing a nonexistent variable or a left value (lvalue) type error
A;//uncaught REFERENCEERROR:A is not defined
1++;//uncaught referenceerror:invalid left-hand side expression in postfix operation
"SyntaxError (syntax error)"
SyntaxError (syntax error) is thrown when the grammar rules are not met
Copy Code code as follows:
Variable name error
var 1a;//uncaught syntaxerror:unexpected number
Missing parentheses
Console.log ' Hello ');//uncaught syntaxerror:unexpected string
"TypeError (type Error)"
A TypeError type error occurs when an unexpected type is saved in a variable, or when a method that does not exist is accessed. The cause of the error is varied, but ultimately it is because the type of the variable does not conform to the requirements when performing a particular type of operation
Copy Code code as follows:
var o = new 10;//uncaught typeerror:10 is not a constructor
Alert (' name ' in true);//uncaught Typeerror:cannot "in" operator to search for ' name ' in true
Function.prototype.toString.call (' name ');//uncaught TypeError:Function.prototype.toString is not generic
"Urierror (URI error)"
Urierror is an error that is thrown when the parameter of the URI-dependent function is incorrect, mainly involving encodeURI (), decodeURI (), encodeURIComponent (), decodeURIComponent (), Escape () and unescape () these six functions
decodeURI ('%2 ');//Urierror:uri Malformed
Error Event
Any error that is not handled by Try-catch triggers the Error event of the Window object
The error event can receive three parameters: the error message, the URL of the error, and the line number. In most cases, only the error message is useful because the URL only gives the location of the document, and the line number refers to the line of code that may originate from embedded JavaScript code or external files
To specify onerror event handlers, you can use DOM0-level techniques, or you can use the standard format for DOM2-level events
Copy Code code as follows:
DOM0 level
Window.onerror = function (message,url,line) {
alert (message);
}
DOM2 level
Window.addeventlistener ("Error", function (message,url,line) {
alert (message);
});
Whether the browser displays standard error messages depends on the return value of the onerror. If the return value is False, an error message is displayed in the console, and if the return value is true, it is not displayed
Copy Code code as follows:
Console displays an error message
Window.onerror = function (message,url,line) {
alert (message);
return false;
}
A
Console does not display error messages
Window.onerror = function (message,url,line) {
alert (message);
return true;
}
A
This event handler is the last line of defense to avoid the browser reporting errors. Ideally, you should not use it whenever possible. As long as you can properly use the Try-catch statement, there will be no error to the browser, and will not trigger the error event
The image also supports the error event. An error event is triggered whenever the URL in the src attribute of the image does not return an image format that can be recognized. The error event in this case follows the DOM format and returns an image-targeted event object
An alert box is displayed when the image is loaded failed. An error event occurs, the image download process has ended, that is, can not be downloaded again
Copy Code code as follows:
var image = new Image ();
IMAGE.SRC = ' smilex.gif ';
Image.onerror = function (e) {
Console.log (e);
}
Throw statement and throw error
The throw statement is used to throw an error. When you throw an error, you must specify a value for the throw statement, what type of value it is, no requirement
[note] The process of throwing an error is blocked and subsequent code will not execute
Copy Code code as follows:
Throw 12345;
Throw ' Hello World ';
throw true;
Throw {name: ' JavaScript '};
You can use the throw statement to manually throw an Error object
Copy Code code as follows:
throw new Error (' Something bad happened ');
throw new SyntaxError (' I don\ ' t like your syntax. ');
throw new TypeError (' What type of variable do you take me for? ');
throw new Rangeerror (' sorry,you just don\ ' t have the range. ')
throw new Evalerror (' that doesn\ ' t evaluate. ');
throw new Urierror (' URI, is ');
throw new Referenceerror (' You didn\ ' t cite your references ');
The prototype chain can also be used to create custom error types by inheriting errors (the prototype chain is described in chapter 6th). At this point, you need to specify the name and message properties for the newly created error type
Browsers treat custom error types that inherit from error, just as they do with other types of errors. It is useful to create a custom error if you want to catch your own thrown error and treat it differently from a browser error
Copy Code code as follows:
function customerror (message) {
this.name = ' customerror ';
this.message = message;
}
Customerror.prototype = new Error ();
throw new Customerror (' My message ');
When the throw statement is encountered, the code stops executing immediately. The code continues to execute only if a Try-catch statement captures the value being thrown
A more detailed explanation is that when an exception is thrown, the JavaScript interpreter immediately stops the currently executing logic and jumps to the nearest exception handler. The exception handler is written in the catch clause of the Try-catch statement. If the code block that throws an exception does not have an associated catch clause, the interpreter checks the closed code block at a higher level to see if it has an associated exception handler. And so on until an exception handler is found. If the function that throws the exception does not have a Try-catch statement to handle it, the exception propagates up to the code that called the function. In this case, the exception propagates up the lexical structure of the JavaScript method and the call stack. If no exception handlers are found, JavaScript treats the exception as a program error and reports it to the user
Try catch statements and catch errors
The 3rd edition of ECMA-262 introduced the Try-catch statement as a standard way to handle exceptions in JavaScript to catch and handle errors
Where the TRY clause defines the code block in which the exception is to be handled. After the catch clause follows the TRY clause, the code logic within the catch is invoked when an exception occurs somewhere inside the try block. The catch clause follows the finally block, where the cleanup code is placed, and the logic in the finally block is always executed, regardless of whether an exception is generated in the try block. Although catch and finally are optional, a try clause requires at least one of the two to form a complete statement
try/catch/finally statement blocks need to be enclosed in curly braces, where curly braces are required, even if only one statement in a clause cannot omit curly braces
try{
Normally, the code here will go from beginning to end without any problems.
Sometimes, however, an exception is thrown, either directly by the throw statement or by invoking a method to throw the
}catch (e) {
The code here executes if and only if the try statement block throws an exception
Here you can get a reference to the Error object or other value thrown by the local variable E
The code block here can handle this exception for some reason, ignore the exception, and then throw the exception back through the throw statement
}finally{
The finally logic executes regardless of whether the try statement throws an exception, and the method that terminates the try statement block is:
1, normal termination, execution of the last statement block statement
2. Terminate by break, continue or return statement
3. Throws an exception, the exception is caught by catch clause
4, throw an exception, the exception is not captured, continue to propagate upward
}
In general, put all the code that might throw the error in a try statement block, and place the code for the error handling in the CATCH block
If any code in the try block has an error, it exits the code execution immediately and then executes the catch block. At this point, the catch block receives an object that has an error message, and the actual information contained in the object will vary by browser, but in common there is a message property that holds the error messages
[note] Be sure to give the Error object a name, empty will report syntax errors
Copy Code code as follows:
try{
Q
}catch (Error) {
alert (error.message);//q is not defined
}
Uncaught syntaxerror:unexpected token)
try{
Q
}catch () {
alert (error.message);
}
Catch accepts a parameter that represents the value thrown by the try code block
Copy Code code as follows:
function Throwit (Exception) {
try {
Throw exception;
catch (e) {
Console.log (' caught: ' + e);
}
}
Throwit (3);//Caught:3
Throwit (' hello ');//Caught:hello
Throwit (new error (' An error happened '))//Caught:Error:An Error happened
Catch code block catch error, program will not be interrupted, will continue to follow the normal process of execution
Copy Code code as follows:
try{
Throw "made a mistake";
catch (e) {
Console.log (111);
}
Console.log (222);
111
222
In order to catch different types of errors, the catch code block can be added to the judgment statement
Copy Code code as follows:
try {
Foo.bar ();
catch (e) {
if (e instanceof evalerror) {
Console.log (E.name + ":" + e.message);
else if (e instanceof rangeerror) {
Console.log (E.name + ":" + e.message);
}
// ...
}
Although the finally clause is optional in the Try-catch statement, the finally clause is used, and its code executes anyway. In other words, the code in the TRY statement block executes normally, the finally clause executes, and the finally clause executes if a catch statement block is executed because of an error. Whenever the code contains a finally clause, no matter what code is contained in a try or catch statement block--even the return statement--does not block the execution of the finally clause
Copy Code code as follows:
The error is not captured because there are no catch statement blocks. After executing the finally code block, the program interrupts where the error is thrown
function Cleansup () {
try {
throw new error (' wrong ... ');
Console.log (' This trip will not execute ');
finally {
Console.log (' Complete clean-up work ');
}
}
Cleansup ();
Finish cleanup work
Error: Wrong ...
Copy Code code as follows:
function testfinnally () {
try{
return 2;
}catch (Error) {
return 1;
}finally{
return 0;
}
}
Testfinnally ();//0
[Note that the value of the count for the]return statement is obtained before the finally code block runs, and gets the complete
Copy Code code as follows:
var count = 0;
function Countup () {
try {
return count;
finally {
count++;
}
}
Countup ();//0
Console.log (count);//1
Copy Code code as follows:
function f () {
try {
Console.log (0);
Throw "Bugs";
catch (e) {
Console.log (1);
return true; This sentence would have been delayed until finally code block is finished and then executed.
Console.log (2); Will not run
finally {
Console.log (3);
return false; This will cover the return of the preceding sentence.
Console.log (4); Will not run
}
Console.log (5); Will not run
}
var result = f ();
0
1
3
Console.log (result);//False
"Tips" block-level scopes
A common use of try-catch statements is to create block-level scopes in which variables declared are valid only within a catch
ES6 introduces the Let keyword and creates block-level scopes for the variables it declares. However, in the case of current ES3 and ES5, try-catch statements are often used to achieve similar effects
The following code shows that e exists only within the catch clause and throws an error when trying to reference it elsewhere
Copy Code code as follows:
try{
throw new error ()//Throw Error
}catch (e) {
Console.log (e);//error (...)
}
Console.log (e);//uncaught referenceerror:e is not defined
Common errors
The core of error handling is to first know what is going to happen in the code. Because JavaScript is loosely typed and does not validate parameters of functions, errors only appear during code. In general, you need to focus on three types of errors: type conversion errors, data type errors, communication errors
"Type conversion Error"
A type conversion error occurs when using an operator, or by using a language structure of another data type that may automatically convert a value
A flow control statement is the place where type conversion errors occur easily. Statements such as if are automatically converted to a Boolean value before the next action is determined. Especially if statements, if used incorrectly, the most error-prone
Unused named variables are automatically assigned undefined values. The undefined value can be converted to a Boolean value of false, so the IF statement in the following function only applies to situations that provide a third parameter. The problem is that not only undefined is converted to false, it is not only string values that can be converted to true. For example, if the third argument is a value of 0, then the test for the IF statement fails, and the test for number 1 passes
Copy Code code as follows:
function Concat (STR1,STR2,STR3) {
var result = str1 + str2;
if (STR3) {//Never do this
result = STR3;
}
return result;
}
The use of non-Boolean values in flow control statements is an extremely common source of error. To avoid such errors, it is necessary to actually pass the Boolean value when the condition is compared. In fact, performing some form of comparison can achieve this goal
Copy Code code as follows:
function Concat (STR1,STR2,STR3) {
var result = str1 + str2;
if (typeof Str3 = = ' string ') {//More appropriate
result = STR3;
}
return result;
}
"Data type Error"
JavaScript is loosely typed and does not compare them to ensure that their data types are correct before using variables and function parameters. To ensure that no data type errors occur, only the appropriate data type instrumentation code can be written. Data type errors are most likely to occur when the expected value is passed to the drawing function
Copy Code code as follows:
Unsafe functions, any non-array values can cause errors
function Reversesort (values) {
if (values) {
Values.sort ();
Values.reverse ();
}
}
Another common mistake is to compare a parameter to a null value. Comparisons with NULL only ensure that the corresponding values are not null and undefined. To ensure that the value passed in is valid, it is not sufficient to detect only null values
Copy Code code as follows:
Unsafe functions, any non-array values can cause errors
function Reversesort (values) {
if (values!= null) {
Values.sort ();
Values.reverse ();
}
}
Passing in an object (instead of an array) that contains the sort () method can be detected, but an error may occur when calling the reverse () function
Copy Code code as follows:
Unsafe functions, any non-array values can cause errors
function Reversesort (values) {
if (typeof values.sort = = ' function ') {
Values.sort ();
Values.reverse ();
}
}
When you know exactly what type you should pass in, it's best to use instanceof to detect its data type
Copy Code code as follows:
Safe, non-array values are ignored
function Reversesort (values) {
if (values instanceof Array) {
Values.sort ();
Values.reverse ();
}
}
"Communication Error"
With the advent of Ajax programming, it has become commonplace for Web applications to dynamically load information or functionality within their lifecycle. However, any communication between JavaScript and the server is likely to produce an error
The most common problem is that the data is not encoded using encodeuricomponent () until the data is sent to the server
Copy Code code as follows:
Error
Http://www.yourdomain.com/?redir=http://www.sometherdomain.com?a=b&c=d
Calling encodeURIComponent () for all strings after ' redir= ' will solve the problem
Http://www.yourdomain.com/?redir=http:%3A%2F%2Fwww.sometherdomain.com%3Fa%3Db%26c%3Dd