程式設計師在工作上一定會遇到的就是寫程式時會出現報錯,這篇文章是基於JavaScript中的錯誤處理部分的概念。希望在大家寫JavaScript程式的時候會幫助大家。
Demo示範
我們使用的Demo可以在GitHub下載,程式運行起來會呈現如下頁面:
##所有的按鈕都會觸發錯誤,拋出TypeError。下面是該模組的定義:// scripts/error.jsfunction error() {var foo = {};return foo.bar();}
// tests/scripts/errorTest.jsit('throws a TypeError', function () {should.throws(error, TypeError);});
// scripts/badHandler.jsfunction badHandler(fn) {try {return fn();} catch (e) { }return null;}
// 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);});
// 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');}}
// scripts/specifiedError.js// Create a custom errorvar SpecifiedError = function SpecifiedError(message) {this.name = 'SpecifiedError';this.message = message || '';this.stack = (new Error()).stack;}; SpecifiedError.prototype = new Error();SpecifiedError.prototype.constructor = SpecifiedError; 、// scripts/uglyHandlerImproved.jsfunction uglyHandlerImproved(fn) {try {return fn();} catch (e) {throw new SpecifiedError(e.message);}}// 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);});
function main(bomb) {try {bomb();} catch (e) {// Handle all the error things}}
// scripts/errorHandlerDom.jswindow.addEventListener('error', function (e) {var error = e.error;console.log(error);});
// 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 detailsxhr.send(message);});
// scripts/asyncHandler.jsfunction asyncHandler(fn) {try {// This rips the potential bomb from the current contextsetTimeout(function () {fn();}, 1);} catch (e) { }}
setTimeout(function () {try {fn();} catch (e) {// Handle this async error}}, 1);
我的建議是不要隱藏錯誤,勇敢地拋出。沒有人會因為程式碼出現bug而導致程式崩潰而羞恥,我們可以讓程式中斷,讓用戶重來。錯誤是無法避免的,如何去處理它才是最重要的。
以上內容就是處理JavaScript報錯時的方法,大家覺得有用的話,趕緊收藏起來吧。
相關推薦:
MySQL資料庫封包錯誤:Too many connections的解決方法
以上是處理JavaScript異常的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!