Post on 18-Jan-2016
transcript
Modern JavaScriptDevelop And Design
Instructor’s NotesChapter 12 – Error Management
Modern JavaScript Design And DevelopCopyright © 2012 by Larry Ullman
Objectives
• Perform exception handling using try…catch
• Add a finally clause to a try statement
• Throw exceptions• Create and use assertions• Implement unit testing
Catching Errors
try { // Lots of code.} catch (error) { // Use error.}
try { doThis(); doThat();} catch (error) { // Use the error somehow.}
The Error Object
try { // Lots of code.} catch (ex) { console.log(error.name + ': ' + error.message + '\n');}
Finally…
try { // Lots of code.} catch (ex) { // Use ex.} finally { // Wrap up.}
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!');
Throwing Exceptions
function $(id) { 'use strict'; if (typeof id != 'undefined') { return document.getElementById(id); } else { throw Error('The function requires one argument.'); }}
Using Assertions
function assert(expression, message) { if (!expression) throw {name: 'Assertion Exception', message: message};}
Unit Testing
• Define tests to confirm specific bits of code work as intended
• Tests should be atomic• Add tests as the project evolves
Using jsUnity
1. Include the framework2. Define tests3. Run tests4. Log results5. Setup and teardown, as needed
Including the Framework
<script src="js/jsunity-0.6.js"></script>
Defining Tests
var myTests = function() { function testThis() { }};
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);
Running Tests
var results = jsUnity.run(myTests);// results.total// results.passed// results.failed// results.duration
Logging Results
jsUnity.log = function(message) { // Do something with message.};