Error handling and testing
One 、 Error handling
One )try-catch sentence
function atest() {
try {
// The code that could have an error
return 0;
} catch (error) {
// Error handler
console.log(error.message);
return 1;
} finally {
// It will be carried out anyway , The function finally returns 2
return 2;
}
}
Wrong type :
1)Error: Error base class , Other error types are inherited by this class .
2)EvalError: Didn't put eval() When the function is called , The error will be sent .
3)RangeError: value out of range
4)ReferenceError: When the object is not found
5)SyntaxError: Pass in eval() Function syntax error
6)TypeError: The type of the variable does not meet the requirements
The rational use of try-catch:
Use try-catch It's best to deal with mistakes that we can't control . Suppose you're using a large JavaScript In the library
function , This function may throw some errors intentionally or unintentionally . Because we can't modify the source code of this library , Therefore, it is possible to reply to the letter
The number of calls is placed in try-catch In the sentence , In case something goes wrong , Or deal with them properly .
When you know your code is going to go wrong , Reuse try-catch The sentence is not suitable . for example , If
The arguments passed to the function are strings, not numbers , It will cause the function to go wrong , You should check the type of the parameter first , And then decide
How to do it . under these circumstances , Don't use try-catch sentence .
Two ) Throw an error
Use throw Operators can throw errors , There is no requirement for the thrown value
// It works
throw 111;
throw ''ss;
In case of throw When the operator , The code will stop executing immediately . Only if try-catch When the statement catches the value being thrown , generation
Code will continue to execute .
By using some built-in error type , More realistic simulation of browser errors . The constructor for each error type takes one parameter
Count , The actual error message .
throw new Error("An error");
When to throw and catch :
Only those errors that you know exactly how to deal with should be caught . Catch the wrong
The goal is to avoid browsers processing them by default ; The purpose of throwing an error is to provide a message about the specific cause of the error .
3、 ... and ) Error events
Anything that doesn't pass try-catch Errors in processing will trigger window Object's error event , In any Web Browser , onerror Event handlers are not created event object ,
But it can take three parameters : Error message 、 What's wrong URL And line number . To specify onerror Event handler , You must use the following DOM0 Level technology , It doesn't follow “DOM2 level
event ” Standard format .
window.onerror = function(msg, url, line) {
log(msg);
// Prevent browsers from reporting errors
return fales;
}
Two 、 test
One ) logging
// One for all browsers log
function log() {
try {
console.log.apply(console, arguments);
}
catch(e) {
try {
opera.postError.apply(opera, arguments);
}
catch (e) {
alert(Array.prototype.join.call(arguments, " "));
}
}
}
Two ) The test case
Three characteristics of a good test case :
1) Reusability : Multiple runs should produce the same result
2) simplicity : Just focus on testing , Eliminate the impact of redundant code
3) independence : Avoid one test result depending on another
3、 ... and ) test suite
The main purpose of the test suite is to aggregate all the individual tests of the code , Combine them into a unit , So they can run in batches , Provide a single resource that can be easily run over and over again .
1) Assertion :
Make an assertion yourself :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
#results li.pass {
color: green;
}
#results li.fail {
color: red;
}
</style>
<body>
<ul id="results"></ul>
</body>
</html>
<script>
function assert(value, desc) {
var liElement = document.createElement("li");
liElement.className = value ? "pass" : "fail";
liElement.appendChild(document.createTextNode(desc));
document.getElementById("results").appendChild(liElement);
}
window.onload = function () {
assert(true, "Success");
assert(false, "Fail");
}
</script>
2) Implementation of test grouping :
(function () {
var results;
this.assert = function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
results.appendChild(li);
if (!value) {
li.parentNode.parentNode.className = "fail";
}
return li;
} this.test = function test(name, fn) {
results = document.getElementById("results");
results = assert(true, name).
appendChild(document.createElement("ul"));
fn();
}
})(); window.onload = function (ev) {
test("all true", function () {
assert(true, "111");
assert(true, "222");
assert(true, "333");
});
test("one false", function () {
assert(false, "failed");
assert(true, "success");
assert(true, "xxx");
});
}
3) Asynchronous test
(function () {
var queue = [], paused = false, results;
this.assert = function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
results.appendChild(li);
if (!value) {
li.parentNode.parentNode.className = "fail";
}
return li;
}; this.test = function test(name, fn) {
queue.push(function () {
results = document.getElementById("results");
results = assert(true, name).
appendChild(document.createElement("ul"));
fn();
});
runTest();
}; function runTest() {
if (!paused && queue.length) {
queue.shift()();
if (!paused) {
resume();
}
}
} this.pause = function () {
paused = true;
}; this.resume = function resume() {
paused = false;
setTimeout(runTest, 1);
}
})(); window.onload = function (ev) {
test("First async test", function () {
pause();
setTimeout(function () {
assert(true, "First async completed!");
resume();
}, 1000);
}); test("Second async test", function () {
pause();
setTimeout(function () {
assert(true, "Second async test completed!");
resume();
}, 1000);
});
}
JavaScript Basic notes ( 13、 ... and ) More articles on testing and debugging
- JavaScript Basic notes collection ( turn )
JavaScript Basic notes collection JavaScript Basic notes collection js brief introduction js It's script language . The browser reads the code line by line , Traditional programming compiles before execution js Storage location html Script must be placed in &l ...
- JavaScript Basic note 2
One . Function return value 1. What is the function return value Function execution result 2. There can be no return // No, return perhaps return If the following is empty, it will return undefined3. A function should return only one type of value Two . variable ...
- JavaScript Basic notes one
One . True and false judgment Really? :true. Non zero number . Non empty string . Non empty object fake :false. The number zero . An empty string . An empty object .undefined example : if(0){ alert(1) }else{ alert(2) } ...
- JavaScript Basic notes ( One ) Basic concepts
Basic concepts One . grammar One ) Case sensitive Two ) identifier The rules of writing are the same as Java 3、 ... and ) notes A little Four ) Strict mode 1. Enable strict mode throughout the script : Add... At the top "use strict" 2. The specified function is in strict ...
- Javascript Basic knowledge test ( One )
Here is a list of < You don't know js> Some knowledge points and small problems in the first volume , If you want to consolidate js Then come and have a look with me . If you can answer without reading 80% My question shows that you js This part of the book is not bad , Make persistent efforts . Scope and ...
- JavaScript Basic notes ( fourteen ) Best practices
Best practices One ) Loose coupling 1. decoupling HTML/JavaScript: 1) avoid html Species usage js 2) avoid js Species creation html 2. decoupling CSS/JS Operation class 3. Decoupling application logic and event handling Here are some applications and ...
- JavaScript Basic notes ( Ten ) Form script
Form script One . Form Basics JavaScript The corresponding form in is HTMLFormElement type , The type inherits from HTMLElement type . adopt document.forms You can get all the form elements , Passing number ...
- JavaScript Basic notes ( 8、 ... and )DOM Expand
DOM Expand One . Selector API Selectors API By W3C It's a standard that's initiated , Committed to native browser support CSS Inquire about . One )querySelector() stay Document and Element Type instance ...
- JavaScript Basic notes 1220
JavaScript note 1.JavaScript key word 2.JavaScript identifier Must be in letters , Underline (_) Or the dollar ($) Start . The following characters can be letters . Numbers . Underline or dollar ( Numbers are not allowed as the first word ...
Random recommendation
- KMP Algorithm
KMP Algorithm is the most classic algorithm in string pattern matching , It turns out that sophomores learn about data structure , But I just remember the principle , But I don't know the code implementation , Today is finally finished KMP Code implementation of . principle KMP It's actually very simple , Given a string and a pattern string ...
- Angular Authoritative guide study notes ( turn )
http://www.cnblogs.com/lzhp/p/4000741.html Chapter one . First time to know Angular——Angular yes MVW Of Js frame . Chapter two . Data binding ...
- How to treat correctly Linq Of DistinctBy Extension and ForEach Expand
In Microsoft standard Linq in , did not DistinctBy Extension and ForEach Expand , But in daily work, we often need to use these two functions , In principle , Microsoft is in Linq These two extensions should be included in , But in fact, why not ? Ben ...
- Various sorting algorithms and c Language implementation
Insertion sort O(n^2) Bubble sort O(n^2) Selection sort O(n^2) Quick sort O(n log n) Heap sort O(n log n) Merge sort O(n log n) Shell Sort O(n^1.25) 1. insert ...
- The application framework is actually 13 :DDD My opinion on layered architecture ( turn )
An important part of the application framework was described earlier —— Public operation class , And provides a data type conversion public operation class as an example to demonstrate . Here's another important part of the application framework , Architecture support . You don't have to use DDD Such an architecture ...
- WeChat official account development 《 3、 ... and 》 WeChat JS-SDK The acquisition of geographical location , Integrating Baidu map to realize online map search
The third part of wechat development : Get user address location information , It's a very common function , Especially the official account of service industry. , This function is particularly needed , This is how to call wechat JS-SDK Interface , Get user location information , Combined with Baidu Metro , Realize online map search , And ...
- About SGA And memory_target The size conflict causes the problem that the database cannot be mounted
About SGA And memory_target The size conflict causes the problem that the database cannot be mounted error message : ORA-00844: Parameter not taking MEMORY_TARGET into accou ...
- Talking about oracle Tree structure level query test data
Talking about oracle Tree structure hierarchical query oracle Tree structure query is hierarchical recursive query , yes sql Sentences are often used , In the actual development, the realization of organizational structure and its hierarchical functions are often encountered , Although I am one java Program developer , I always thought it was just ...
- 【BZOJ1146】 Network management ( Chairman tree , Tree array )
[BZOJ1146] Network management ( Chairman tree , Tree array ) Topic BZOJ Authority questions , Luogu topic Answer key There is a chairman tree on the tree It seems to be and \(Count\ On\ A\ Tree\) That question is very similar You just need to set up a tree array to maintain ...
- 【Python 25】52 Zhou cunqian challenges 5.0(datetime Kuhe import)
1. Case description according to 52 The weekly savings method , The depositor has to be in a year 52 bring a false charge against an innocent person , Every week 10 element . for example , The first week 10 element , The second week 20 element , The third week 30 element , Until the first 52 Zhou Cun 520 element . Record 52 How much can I save in a week ? namely 10+20+30+. ...