js error 錯誤處理


(new) Error([message[, fileName[,lineNumber]]])
單獨定義Error()錯誤,函數繼續進行

當像函數一樣使用 Error 時 -- 如果沒有 new,它將返回一個 Error 對象。所以, 僅僅調用 Error 產生的結果與通過new 關鍵字構造 Error 對象生成的結果相同。 

// this:
const x = Error('I was created using a function call!');
​​​​//與上面一樣
const y = new Error('I was constructed via the "new" keyword!');

Error 類型

ReferenceError引用變量不存在錯誤  obj.a  

TypeError  類型錯誤

let a=undefined |null
a.name

let num={}
num.fn()

SyntaxError 語法錯誤 let num=10++2

 


出現錯誤,代碼不會執行的情況:1.觸發了常見內置錯誤ReferenceError、TypeError ...2. 主動拋出錯誤throw Error
出現了錯誤就需要try-catch捕獲錯誤 代碼才會繼續向下進行
let a = null
try {
  a.name //error.name=TypeError ;  error.message=Cannot read property 'name' of null(觸發內置)
  obj.xxx //error.name=ReferenceError ;  error.message=obj is not defined (觸發內置)

} catch (error) {
  console.log(error.message, error.name);//error.message錯誤信息 ,error.name錯誤類型

}



function permit(age) {
  if (age > 18) {
    console.log('permission');

  } else {
    throw new Error('age is less 18 ,you have not right') //自己主動拋錯誤
  }
}

try {
  permit(3)
} catch (error) {
  console.log(error.name, error.message); //error.name=Error; error.message=age is less 18 ,you have not right
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM