IE10 Error. stack makes script debugging more convenient and convenient

Source: Internet
Author: User

Comments: The Error. stack support has been added to IE10 to speed up script debugging and correct errors. Especially some errors that are hard to reproduce, such as asynchronous operations.

The Error. stack support has been added to IE10 to speed up script debugging and correct errors. Especially some errors that are hard to reproduce, such as asynchronous operations. The following content is from the Microsoft IE team, which describes this feature in great detail.

Debug the application

Structured error handling in JavaScript depends onthrowAndtry/catch, The developer will declare an error in it and pass the control flow to a part of the program that handles the error. When an error is thrown, Chakra, that is, the JavaScript engine in Internet Explorer, captures the call chain that triggers the error. This process is also called the call stack. If the object to be thrown isError(Or a function, and its prototype chain will causeError), Then Chakra will create a stack trace to manually read the call stack list. This list is represented as an attribute, that isErrorObjectstack.stackContains the error message, function name, and source file location information of the function. This information helps developers understand the called functions, and even view wrong code lines, so as to quickly diagnose defects. For example, the information may indicate that a parameter passed to the function is null or invalid.

Let's take a look at a simple script and discuss it in depth. This script is trying to calculate(0, 2)And(12, 10)Distance between two points:

The Code is as follows:
(Function (){
'Use strict ';
Function squareRoot (n ){
If (n <0)
Throw new Error ('could not take square root of negative number .');
Return Math. sqrt (n );
}
Function square (n ){
Return n * n;
}
Function pointDistance (pt1, pt2 ){
Return squareRoot (pt1.x-pt2.x) + (pt1.y-pt2.y ));
}
Function sample (){
Var pt1 = {x: 0, y: 2 };
Var pt2 = {x: 12, y: 10 };
Console. log ('distance is: '+ pointDistance (pt1, pt2 ));
}
Try {
Sample ();
}
Catch (e ){
Console. log (e. stack );
}
})();

This script contains a defect that does not adjust the differences between components. Therefore, for some input,pointDistanceThe function returns an error. In other cases, this script causes the error. To understand the meaning of stack tracing, let's check the errors in the F12 developer tool and its script tab:

Stack trace will be dumpedcatchConsole in the clause, because it is located at the top of the stack, it originated fromsquareRootFunction errors become obvious. To debug this problem, developers do not need to view the stack trace in depth; the system has violatedsquareRootAnd you only need to view the upper level of the stack, the reason will become very clear:squareRootThe subexpression in the call should besquare.

During debugging,stackAttribute helps identify the code used to set breakpoints. Remember: you can also use other methods to view the call stack. For example, if you set the script debugging program to the "Capture exceptions or interrupt" mode, you can use this debug program to check the call stack. For deployed applications, you can considertry/catchTo capture failed calls and record them in the server. Then, developers can view the call stack to isolate the problem area.

DOM exception and Error. stack

Previously, I noticed that the object to be thrown must beErrorOr caused by its prototype chainError. This is intended for it; JavaScript supports triggering any object, or even a primitive that serves as an exception. Although the system can capture and check all these objects, their full use does not contain error or diagnostic information. Therefore, onlystackAttribute.

Even if the object is a DOM exception, they do not containErrorPrototype chain, so they will not containstackAttribute. In some application scenarios, you may want to perform DOM operations and expose JavaScript-compatible errors.try/catch Merge your DOM operation code in the data block andcatchClause raises a newErrorObject:

The Code is as follows:
Function causesDomError (){
Try {
Var div = document. createElement ('div ');
Div. appendChild (div );
} Catch (e ){
Throw new Error (e. toString ());
}
}

However, you may consider whether to use this mode. This may be the most suitable mode for utility library development, especially when you consider whether the code intent is to hide DOM operations or simply implement a task. If the objective is to hide the DOM operation, the merge operation is triggeredErrorIt may be the correct method we need to choose.

Performance Considerations

The construction of a stack trace starts when an error object is thrown. To construct a stack trace, You need to view the current execution stack. To prevent performance problems (or even recursive stack traces) during the process of traversing a super-large stack, by default, IE collects only the top 10 stack frames. However, you can set the static attributeError.stackTraceLimitSet it to another value. This setting is global and must be changed before an error is thrown. Otherwise, it will be invalid for Stack tracking.

Asynchronous exception

When a stack is asynchronously called back (for exampletimeout,intervalOrXMLHttpRequest), The asynchronous callback (rather than the Code created by the asynchronous callback) will be at the bottom of the call stack. This will have some potential impact on code with tracing problems: if you use the same callback function for multiple asynchronous callbacks, it is difficult for you to identify which callback generates an error by checking it separately. Let's make a slight modification to the previous example, and we will avoid direct callssample(), But put it into the timeout callback:

The Code is as follows:
(Function (){
'Use strict ';
Function squareRoot (n ){
If (n <0)
Throw new Error ('could not take square root of negative number .');
Return Math. sqrt (n );
}
Function square (n ){
Return n * n;
}
Function pointDistance (pt1, pt2 ){
Return squareRoot (pt1.x-pt2.x) + (pt1.y-pt2.y ));
}
Function sample (){
Var pt1 = {x: 0, y: 2 };
Var pt2 = {x: 12, y: 10 };
Console. log ('distance is: '+ pointDistance (pt1, pt2 ));
}
SetTimeout (function (){
Try {
Sample ();
}
Catch (e ){
Console. log (e. stack );
}
},2500 );
})();

Once you execute this code segment, you will find that the stack trace has a slight delay. At this time, you will also find that the bottom of the stack is not a global code,Anonymous function. In fact, this is not the same anonymous function, but passedsetTimeout. Because you have lost the context related to the suspended callback, you may not be able to determine the content of the called callback. In an application scenario, the system registers a callback to process multiple buttons.clickEvent, you cannot tell which callback will be referenced by registration. Even so, this restriction is limited, because in most cases, the top of the stack may highlight the problem area.

Demonstration of viewing experience

Learn about IE10 usage in Windows 8 Consumer Preview. You canevalIf an error occurs, you can check the error. If you run the code within IE10, You can hover the error code line over the stack trace, so you can highlight your code line. You can enter the code in the code area or select from several examples in the list. You can also setError.stackTraceLimitValue.

For more information, seeError.stackAndstackTraceLimit.


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.