JS 常見的報錯及異常捕獲
在開發中,有時,我們花了幾個小時寫的 Js 代碼,在遊覽器調試一看,控制檯一堆紅,瞬間一萬頭草泥馬奔騰而來。
至此,本文主要記錄 Js 常見的一些錯誤類型,以及常見的報錯信息,分析其報錯原因,並給予處理方法。並且將介紹幾種捕獲異常的方法。
注:本文使用的谷歌遊覽器驗證,不同的遊覽器,報錯可能會不一樣。
正文
常見的錯誤類型
-
RangeError:標記一個錯誤,當設置的數值超出相應的範圍觸發。比如,new Array(-20)。
-
ReferenceError:引用類型錯誤,當一個不存在的變量被引用時發生的錯誤。比如:console.log(a)。
-
SyntaxError:語法錯誤。比如 if(true) {。
-
TypeError:類型錯誤,表示值的類型非預期類型時發生的錯誤。
常見的錯誤
RangeError: Maximum call stack size exceeded
含義:超出了最大的堆棧大小
爲什麼報錯?
在使用遞歸時消耗大量堆棧,導致遊覽器拋出錯誤,因爲遊覽器給分配的內存不是無限的。
舉個栗子 → 🙌🌰
function pow(x, n) {
return x * pow(x, n - 1);
}
pow(10,5)
處理辦法
使用遞歸的時候,設定一個條件來終止遞歸,否則會無限循環,直到用盡調用堆棧空間爲止。
function pow(x, n) {
if (n == 1) return x
return x * pow(x, n - 1);
}
pow(10,5)
ReferenceError: "x" is not defined
含義:“x” 未定義
爲什麼報錯?
當你引用一個沒有定義的變量時,拋出一個 ReferenceError; 當你使用變量的時候,這個變量必須要聲明,或者你可以確保它在你當前的腳本或作用域 (scope) 中可用。
舉個栗子 → 🙌🌰
// 變量未聲明
console.log(a)
fn()
// 錯誤的作用域
function sum() {
let number1 = 20,number2 = 30;
return number1 + number2;
}
console.log(number1)
處理辦法
變量使用 var|let|const 聲明
提升變量的作用域
// 變量未聲明
let a;
function fn() {};
console.log(a);
fn();
// 錯誤的作用域
let number1 = 20, number2 = 30;
function sum() {
return number1 + number2;
}
console.log(number1)
SyntaxError: Identifier 'x' has already been declared
含義: 標識符已申明
爲什麼報錯?
某個變量名稱已經作爲參數出現了,又在使用 let 再次聲明。
舉個栗子 → 🙌🌰
// let 重複聲明
let a = 0;
let a = 2;
// 在函數中參數已經出現,函數里使用let重新聲明
function fn(arg) {
let arg = []
}
SyntaxError: Invalid or unexpected token
含義:捕獲無效或意外的標記
爲什麼報錯?
代碼中有非法的字符或者缺少必要的標識符號,比如減號 (-) 與連接符 ( – ) ,或者是英文雙引號 ( " ) 與中文雙引號 ( “ )。
舉個栗子 → 🙌🌰
// 遺漏的字符
let str = 'string;
let colors = ['#000', #333', '#666'];
// 使用特殊字符
let str1 = 'string";
let str2 = 5#5;
// 錯配字符(使用中文引號字符)
let str3 = ‘string’;
處理辦法
檢查是否有特殊字符或者是否遺漏一些字符。
SyntaxError: Unexpected end of input
含義:意外的終止輸入
爲什麼報錯?
代碼中某些地方的括號或引號不匹配缺失,缺少 ()、[]、{} 等。
舉個栗子 → 🙌🌰
// 缺少括號
if(true)
let obj = {id: 1
let arr = [1,2,3
// 缺少結束符號
(function () {
console.log('hello world')
}()
處理辦法
檢查是否有特殊字符或者是否遺漏一些字符, 括號需要配對出現。
TypeError: Cannot read property 'x' of undefined
TypeError: Cannot set property 'x' of undefined
含義:無法讀取屬性‘x’, 無法設置屬性'x'
爲什麼報錯?
訪問或設置未定義 (undefined) 或 null 值的屬性時會發生這種報錯。
舉個栗子 → 🙌🌰
// undefined
let a = undefined
a.id // 讀取
a.id = 1 // 設置
// null
let b = null
b.id // 讀取
b.id = 2 // 設置
null.filter(item=>item)
處理辦法
有一些方法可以避免這種錯誤。一種簡單且適用於小型屬性鏈的方法是使用邏輯運算符 &&。
let obj = undefined
console.log(obj&&obj.id)
TypeError: 'x' is not a constructor
含義:表示 ‘x’不是構造函數
爲什麼報錯?
使用不是構造器的對象或者變量來作爲構造器使用。比如:new 10。
舉個栗子 → 🙌🌰
let Car = 1;
new Car();
new Math();
處理辦法
使用正確的構造函數。Generator functions 也不能作爲構造器來使用。
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
SyntaxError: Invalid regular expression flags
含義:正則表達式標誌無效
爲什麼報錯?
在代碼中出現了無效的正則表達式的標記。
舉個栗子 → 🙌🌰
let reg = /foo/bar;
處理辦法
let reg = /foo/g;
DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
含義:無效的 Url
爲什麼報錯?
在使用 ajax 請求時 url 錯誤,導致請求失敗。
舉個栗子 → 🙌🌰
function createXHR(url) {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function () {
}
}
createXHR('http://192.168.10.8080') // 錯誤url
createXHR('http:/192.168.10:8080/open') // 缺少 /,注:有些遊覽器會自動補全
處理辦法
檢查 url 請求是否正確,保證請求路徑的完整。
createXHR('http://192.168.10:8080')
異常調試及捕獲
-
try/catch,Js 中處理異常的一種模式,
try
用於可能會發生錯誤的代碼,catch
對錯誤的處理try{ // 可能會導致錯誤的代碼 }catch(error) { // 錯誤處理 }
舉個栗子 → 🙌🌰
try{ console.log(a) }catch(error) { // 打印錯誤信息 console.log(error) // ReferenceError: a is not defined }
-
throw,用來拋出一個用戶自定義的異常,執行將被停止。
function getUserName(name) { if(!name) throw new Error('用戶名無效'); return name; } getUserName()
-
Promise 的異常處理, Promise 執行中,本身自帶 try...catch 的異常處理,出錯時,將錯誤 Rejact 函數。
new Promise((resolve, reject) => { throw new Error('error!'); }).catch(alert);
-
console.log() 方法, 在遊覽器中,使用 console.log 打印 javaScript 的值。
let value = '你最棒了,點個讚唄!' console.log(value)
-
debugger 斷點調試,用於停止執行 JavaScript,並調用調試函數。
let value = 15; debugger document.querySelector('body').innerHTML = '你最棒了,點個讚唄!'
總結
報錯的時候別慌,有時候就是那麼簡單,根據這些代碼敲一敲,熟悉一些常用的報錯信息,便於在報錯的時候快速的定位到報錯原因。希望對面的小可愛們有所收穫。
作者:FishStudy520
https://segmentfault.com/a/1190000038323321
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/Kfni_95-eJzhqW1rSYCOzg