Read JavaScript Advanced programming 14-Error handling and debugging

Source: Internet
Author: User

One error type

The ECMA specifies 7 common types of errors:

    • Error: Base type. Other common error types are inherited from this type, and are typically used by developers to throw custom errors.
    • Evalerror: This type is thrown when the eval () function uses an exception. For example: New Eval ();. In fact, in some versions of the browser will be thrown typeerror, and the eval () function itself in the actual development of the use of caution, so the probability of throwing evalerror is very small.
    • Rangeerror: Triggered when the value is out of range. For example: New Array ( -1)//rangeerror:invalid array length.
    • Referrererror: This error is usually triggered when a variable that does not exist is accessed. For example: Console.log (a);//REFERENCEERROR:A is not defined
    • SyntaxError: This type error is usually triggered when a syntactically incorrect JavaScript string is passed to the eval () function. Eval ("Console.log (a) +")
    • TypeError: When a specific operation is performed, a type error occurs if the variable type does not conform. There are several common situations where you can access a nonexistent method, a function passed into a parameter type that does not conform, and so on.
    • Urierror: This error occurs when the encodeURI () and decodeURI () methods are used, and the URI is not in the correct format.

In cross-browser programming, pre-checking the type of error is one way to determine how to handle it, which is to first catch the error with the Try-catch statement, then use the instanceof operator in the catch block to determine the type of error, and then make the appropriate processing based on the different error types.

Try {new 1catch  (error) {ifinstanceof  evalerror) { Console.log (' eval parameter error 'elseifinstanceof  TypeError) { Console.log (' type error 'else  {console.log (error.message);}}
two catching errors and throwing errors

1.try-catch Statement Catch Error

The Try-catch statement is a common way to catch errors. Where catch receives an object that contains an error message, and if the object is not used, give it a name, or a syntax error will occur. The object error in the catch has a generic property message that holds the specific error message.

Try {  catch  (error) {  alert (error.message);}

Finally clause: for cases with a finally clause, whether it is executing a try branch or a catch branch, the finally branch is definitely executed. Even if a return statement is in the middle, the execution of the finally clause cannot be prevented.

Try {  Console.log (1catch  (error) {  Console.log (2finally  {  console.log (3);}

Try-catch is suitable for handling errors that we cannot control.

2. Throwing errors

The throw operator is used to throw an error, and the code will stop executing immediately when the operator is encountered, and the code will continue to execute only if the Try-catch statement snaps to the thrown value. You can simulate browser errors more realistically by using a built-in error type. For example:

Throw New Error ("Test throw error");

The more common type of error is error,rangeerror,referenceerror,typeerror.

Using the prototype chain, you can create custom error types by inheriting error. For example:

function myerror (message) {this. Name = ' Myerror '; this. Message =new  Error (); Throw New Myerror (' This is my test error; ');

For code-heavy programs, it is often difficult to locate errors directly based on the original error message. Custom errors with appropriate information can show the avatar, significantly improving the maintainability of the Code. In the development process, it is particularly important to focus on the function and the location that is prone to failure of function execution. such as the test of the parameter type. For example:

function Test (value) {ifinstanceof  Array)) {thrownew Error (' Test (): parameter is not an array ');} return value.sort ();}

In summary, the purpose of throwing an error is to provide detailed information about the specific cause of the error, and the purpose of the catch error is to prevent the browser from handling the error in the default manner.

three several common error scenarios

JavaScript is loosely typed and does not validate parameter types when it is passed, so errors occur during code execution. The three common error types are: type conversion errors, data type errors, and communication errors.

1. Type conversion error

Type conversion errors often occur in scenarios where an operator is used or the data type is automatically converted.

The first common error is the use of equal and unequal operators

Console.log (1== "1"); // trueconsole.log (1==true); // true

Improvement: It is recommended to use the congruent (= = =) and non-congruent (!==) operators to avoid the type conversion errors that arise when using equality and inequality operators;

Console.log (1=== "1"); // falseConsole.log (1===true); // false

The second common mistake is to use a non-Boolean value in a flow control statement.

function concat (str1,str2) {if(str2) {return str1+str2;} Else {return  str1;}} Concat (' a ', 0); // a "concat (' A ', 1); // "A1"

The purpose of this method is to return two string concatenation results when the second argument is present, and to return the first argument directly when the second parameter does not exist. However, except that the undefined will be converted to a Boolean value of False, 0 will also be converted to false. and 1 is converted to true. Therefore, the call result is not consistent with the original intention.

Improved:

function concat (str1,str2) {if(typeof str2== "string") {return str1+str2;} Else {return  str1;}} Concat (' a ', 0); // a "concat (' A ', 1); // "a"

2. Data type Error

In JavaScript, type checking is not done automatically before using variables and function parameters. Therefore, developers are required to write their own code for data type detection. For example:

function Reversesort (values){if (values) {// ) The judgment here is not guaranteed to be an array type values.sort (); Values.reverse ();} Console.log (values); }reversesort ("a"); // TypeError

Here, if the parameter passed in is not an array type, a data type error occurs. Generally speaking, type checking is done using typeof for the base type, and instanceof for the object type.

function Reversesort (values) {ifinstanceof  Array) {values.sort (); Values.reverse ();} Console.log (values);} Reversesort ("a"); // a "reversesort ([6,2,3,8,1,5]); // [8, 6, 5, 3, 2, 1]

3. Communication error

The first scenario is that the data is not encoded using encodeuricomponent () before the data is sent to the server. For example:

Www.cnblogs.com?backurl=http
://www.cnblogs.com?a=1

The workaround is to encode the parameters following the Backurl using encodeURIComponent (), with the result:

Www.cnblogs.com?backurl= HTTP%3A%2F%2FWWW.CNBLOGS.COM%3FA%3D1

Scenario two is for the query string, and also for the name and value of the query parameter are encoded.

Four logging errors to the server

If the error information in the front and back end of the summary record, can greatly facilitate the analysis of the database error log. To log javascrpt errors to the server requires an image control because all browsers support image objects and can avoid cross-domain restrictions.

Start by creating a new server page to handle the error data. This page gets the error data from the query string, and then writes the data to the error log, for example, the page is a.ashx.

Then, in the Call page, create an Image object and assign a value to its SRC attribute so that the error message can be sent to the server page.

function LogError (msg) {varnew= ' a.ashx?msg= ' + encodeuricomponent (msg);}

Read JavaScript Advanced programming 14-Error handling and debugging

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.