Download presentation
Presentation is loading. Please wait.
Published byBrook Wilkerson Modified over 9 years ago
1
Modern JavaScript Develop And Design Instructor’s Notes Chapter 12 – Error Management Modern JavaScript Design And Develop Copyright © 2012 by Larry Ullman
2
Objectives Perform exception handling using try…catch Add a finally clause to a try statement Throw exceptions Create and use assertions Implement unit testing
3
Catching Errors try { // Lots of code. } catch (error) { // Use error. } try { doThis(); doThat(); } catch (error) { // Use the error somehow. }
4
The Error Object try { // Lots of code. } catch (ex) { console.log(error.name + ': ' + error.message + '\n'); }
5
Finally… try { // Lots of code. } catch (ex) { // Use ex. } finally { // Wrap up. }
6
Throwing Exceptions throw something; throw 2; // Assumes 2 is meaningful in the catch. throw 'No such HTML element!'; throw new Error('No such HTML element!');
7
Throwing Exceptions function $(id) { 'use strict'; if (typeof id != 'undefined') { return document.getElementById(id); } else { throw Error('The function requires one argument.'); }
8
Using Assertions function assert(expression, message) { if (!expression) throw {name: 'Assertion Exception', message: message}; }
9
Unit Testing Define tests to confirm specific bits of code work as intended Tests should be atomic Add tests as the project evolves
10
Using jsUnity 1.Include the framework 2.Define tests 3.Run tests 4.Log results 5.Setup and teardown, as needed
11
Including the Framework
12
Defining Tests var myTests = function() { function testThis() { } };
13
Assertion Methods assertTrue() assertFalse() assertIdentical() assertNotIdentical() assertEqual() assertNotEqual() assertTypeOf() assertNotTypeOf() assertInstanceOf() assertNull() assertNotNull() assertUndefined() jsUnity.assertions.assertNotUndefined(myVar); jsUnity.assertions.assertTypeOf('number', radius); jsUnity.assertions.assertNotNaN(volume);
14
Running Tests var results = jsUnity.run(myTests); // results.total // results.passed // results.failed // results.duration
15
Logging Results jsUnity.log = function(message) { // Do something with message. };
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.