// tests/scripts/badHandlerTest.jsit('returns a value without errors', function() { var fn = function() { return 1;
}; var result = badHandler(fn);
result.should.equal(1);
});
it('returns a null with errors', function() { var fn = function() { throw new Error('random error');
}; var result = badHandler(fn);
should(result).equal(null);
});
如果出现问题,错误处理程序就会返回 null。fn( ) 回调函数可以指向一个合法的方法或错误。
以下的点击事件会继续进行事件处理:
// scripts/badHandlerDom.js(function (handler, bomb) { var badButton = document.getElementById('bad'); if (badButton) {
badButton.addEventListener('click', function () {
handler(bomb);
console.log('Imagine, getting promoted for hiding mistakes');
});
}
}(badHandler, error));
// scripts/uglyHandler.jsfunction uglyHandler(fn) { try { return fn();
} catch (e) { throw new Error('a new error');
}
}
处理异常的方式如下所示:
// tests/scripts/uglyHandlerTest.jsit('returns a new error with errors', function () { var fn = function () { throw new TypeError('type error');
};
should.throws(function () {
uglyHandler(fn);
}, Error);
});
// tests/scripts/uglyHandlerImprovedTest.jsit('returns a specified error with errors', function () { var fn = function () { throw new TypeError('type error');
};
should.throws(function () {
uglyHandlerImproved(fn);
}, SpecifiedError);
});
// scripts/errorAjaxHandlerDom.jswindow.addEventListener('error', function (e) { var stack = e.error.stack; var message = e.error.toString(); if (stack) {
message += '\n' + stack;
} var xhr = new XMLHttpRequest();
xhr.open('POST', '/log', true); // Fire an Ajax request with error details xhr.send(message);
});
// scripts/asyncHandler.jsfunction asyncHandler(fn) { try { // This rips the potential bomb from the current context
setTimeout(function () {
fn();
}, 1);
} catch (e) { }
}
通过单元测试来查看问题:
// tests/scripts/asyncHandlerTest.jsit('does not catch exceptions with errors', function () { // The bomb
var fn = function () { throw new TypeError('type error');
}; // Check that the exception is not caught
should.doesNotThrow(function () {
asyncHandler(fn);
});
});