知道 JavaScript 中的錯誤對象有哪些類型嗎?

做者:Isha Jauhari 譯者:前端小智 來源:dottorophp

點贊再看,養成習慣前端

本文 GitHub github.com/qq449245884… 上已經收錄,更多往期高贊文章的分類,也整理了不少個人文檔,和教程資料。歡迎Star和完善,你們面試能夠參照考點複習,但願咱們一塊兒有點東西。git

每當 JavaScript 中發生任何運行時錯誤時,都會引起Error對象。 在許多狀況下,咱們還能夠擴展這些標準Error對象,以建立咱們本身的自定義Error對象。github

屬性

Error 對象具備2個屬性面試

name ——設置或返回錯誤名稱。具體來講,它返回錯誤所屬的構造函數的名稱。數組

它有6個不一樣的值-EvalErrorRangeErrorReferenceErrorTypeErrorSyntaxErrorURIError。 咱們將在本文後面討論這些內容,這些全部錯誤類型均繼承自Object-> Error-> RangeError瀏覽器

message-設置或返回錯誤消息bash

事例

1.通用的錯誤微信

咱們可使用Error對象建立一個新的Error,而後使用throw關鍵字顯式拋出該錯誤。ide

try{
    throw new Error('Some Error Occurred!')
} 
catch(e){
    console.error('Error Occurred. ' + e.name + ': ' + e.message)
}
複製代碼

2.處理特定的錯誤類型

咱們還可使用以下的instanceof關鍵字來處理特定的錯誤類型。

try{
    someFunction()
} 
catch(e){
    if(e instanceof EvalError) {
    console.error(e.name + ': ' + e.message)
  } 
  else if(e instanceof RangeError) {
    console.error(e.name + ': ' + e.message)
  }
  // ... something else
}
複製代碼

3.自定義錯誤類型

咱們還能夠經過建立繼承Error對象的類來定義本身的錯誤類型。

class CustomError extends Error {
  constructor(description, ...params) {
    super(...params)
    
    if(Error.captureStackTrace){
      Error.captureStackTrace(this, CustomError)
    }
    this.name = 'CustomError_MyError'
    this.description = description
    this.date = new Date()
  }
}
try{
  throw new CustomError('Custom Error', 'Some Error Occurred')
} 
catch(e){
  console.error(e.name)           //CustomError_MyError
  console.error(e.description)    //Custom Error
  console.error(e.message)        //Some Error Occurred
  console.error(e.stack)          //stacktrace
}
複製代碼

瀏覽器兼容性

Error 的對象類型

如今讓咱們討論可用於處理不一樣錯誤的不一樣錯誤對象類型。

1. EvalError

建立一個error實例,表示錯誤的緣由:與 eval() 有關。

這裏要注意的一點是,當前ECMAScript規範不支持它,而且運行時不會將其拋出。 取而代之的是,咱們可使用SyntaxError錯誤。可是,它仍然能夠與ECMAScript的早期版本向後兼容。

語法

new EvalError([message[, fileName[, lineNumber]]])
複製代碼

事例

try{
  throw new EvalError('Eval Error Occurred');
} 
catch(e){
  console.log(e instanceof EvalError); // true
  console.log(e.message);    // "Eval Error Occurred"
  console.log(e.name);       // "EvalError"
  console.log(e.stack);      // "EvalError: Eval Error Occurred..."
}
複製代碼

瀏覽器兼容性

2. RangeError

建立一個error實例,表示錯誤的緣由:數值變量或參數超出其有效範圍。

new RangeError([message[, fileName[, lineNumber]]])
複製代碼

下面的狀況會觸發該錯誤:

1)根據String.prototype.normalize(),咱們傳遞了一個不容許的字符串值。

// Uncaught RangeError: The normalization form should be one of NFC, NFD, NFKC, NFKD
String.prototype.normalize(「-1」)
複製代碼

2)使用Array構造函數建立非法長度的數組

// RangeError: Invalid array length
var arr = new Array(-1);
複製代碼

3)諸如 Number.prototype.toExponential()Number.prototype.toFixed()Number.prototype.toPrecision()之類的數字方法會接收無效值。

// Uncaught RangeError: toExponential() argument must be between 0 and 100
Number.prototype.toExponential(101)
// Uncaught RangeError: toFixed() digits argument must be between 0 and 100
Number.prototype.toFixed(-1)
// Uncaught RangeError: toPrecision() argument must be between 1 and 100
Number.prototype.toPrecision(101)
複製代碼

事例

對於數值

function checkRange(n)
{
    if( !(n >= 0 && n <= 100) )
    {
        throw new RangeError("The argument must be between 0 and 100.");
    }
};
try
{
    checkRange(101);
}
catch(error)
{
    if (error instanceof RangeError)
    {
        console.log(error.name);
        console.log(error.message);
    }
}
複製代碼

對於非數值

function checkJusticeLeaque(value)
{
    if(["batman", "superman", "flash"].includes(value) === false)
    {
        throw new RangeError('The hero must be in Justice Leaque...');
    }
}
try
{
    checkJusticeLeaque("wolverine");
}
catch(error)
{
    if(error instanceof RangeError)
    {
        console.log(error.name);
        console.log(error.message);
    }
}
複製代碼

瀏覽器兼容性

3. ReferenceError

建立一個error實例,表示錯誤的緣由:無效引用。

new ReferenceError([message[, fileName[, lineNumber]]])
複製代碼

事例

ReferenceError被自動觸發。

try {
  callJusticeLeaque();
} 
catch(e){
  console.log(e instanceof ReferenceError)  // true
  console.log(e.message)        // callJusticeLeaque is not defined
  console.log(e.name)           // "ReferenceError"
  console.log(e.stack)          // ReferenceError: callJusticeLeaque is not defined..
}
or as simple as 
a/10;
複製代碼

顯式拋出ReferenceError

try {
  throw new ReferenceError('Reference Error Occurred')
} 
catch(e){
  console.log(e instanceof ReferenceError)  // true
  console.log(e.message) // Reference Error Occurred
  console.log(e.name)   // "ReferenceError"
  console.log(e.stack)  // ReferenceError: Reference Error Occurred.
}
複製代碼

瀏覽器兼容性

4. SyntaxError

建立一個error實例,表示錯誤的緣由:eval()在解析代碼的過程當中發生的語法錯誤。

換句話說,當 JS 引擎在解析代碼時遇到不符合語言語法的令牌或令牌順序時,將拋出SyntaxError

捕獲語法錯誤

try {
  eval('Justice Leaque');  
} 
catch(e){
  console.error(e instanceof SyntaxError);  // true
  console.error(e.message);    //  Unexpected identifier
  console.error(e.name);       // SyntaxError
  console.error(e.stack);      // SyntaxError: Unexpected identifier
}

let a = 100/; // Uncaught SyntaxError: Unexpected token ';'
// Uncaught SyntaxError: Unexpected token ] in JSON
JSON.parse('[1, 2, 3, 4,]'); 
// Uncaught SyntaxError: Unexpected token } in JSON
JSON.parse('{"aa": 11,}');
複製代碼

建立一個SyntaxError

try {
  throw new SyntaxError('Syntax Error Occurred');
} 
catch(e){
  console.error(e instanceof SyntaxError); // true
  console.error(e.message);    // Syntax Error Occurred
  console.error(e.name);       // SyntaxError
  console.error(e.stack);      // SyntaxError: Syntax Error Occurred
}
複製代碼

瀏覽器兼容性

5. TypeError

建立一個error實例,表示錯誤的緣由:變量或參數不屬於有效類型。

new TypeError([message[, fileName[, lineNumber]]])
複製代碼

下面狀況會引起 TypeError

  • 在傳遞和預期的函數的參數或操做數之間存在類型不兼容。
  • 試圖更新沒法更改的值。
  • 值使用不當。

例如:

const a = 10;
a = "string"; // Uncaught TypeError: Assignment to constant variable

null.name // Uncaught TypeError: Cannot read property 'name' of null
複製代碼

捕獲TypeError

try {
  var num = 1;
  num.toUpperCase();
} 
catch(e){
  console.log(e instanceof TypeError)  // true
  console.log(e.message)   // num.toUpperCase is not a function
  console.log(e.name)      // "TypeError"
  console.log(e.stack)     // TypeError: num.toUpperCase is not a function
}
複製代碼

建立 TypeError

try {
  throw new TypeError('TypeError Occurred') 
} 
catch(e){
  console.log(e instanceof TypeError)  // true
  console.log(e.message)          // TypeError Occurred
  console.log(e.name)             // TypeError
  console.log(e.stack)            // TypeError: TypeError Occurred
}
複製代碼

瀏覽器兼容性

6. URIError

建立一個error實例,表示錯誤的緣由:給 encodeURI()或 decodeURl()傳遞的參數無效。

若是未正確使用全局URI處理功能,則會發生這種狀況。

簡單來講,當咱們將不正確的參數傳遞給encodeURIComponent()decodeURIComponent()函數時,就會引起這種狀況。

new URIError([message[, fileName[, lineNumber]]])
複製代碼

encodeURIComponent()經過用表示字符的UTF-8編碼的一個,兩個,三個或四個轉義序列替換某些字符的每一個實例來對URI進行編碼。

// "https%3A%2F%2Fmedium.com%2F"
encodeURIComponent('https://medium.com/');
複製代碼

decodeURIComponent()——對以前由encodeURIComponent建立的統一資源標識符(Uniform Resource Identifier, URI)組件進行解碼。

// https://medium.com/
decodeURIComponent("https%3A%2F%2Fmedium.com%2F")
複製代碼

捕捉URIError

try {
  decodeURIComponent('%')
} 
catch (e) {
  console.log(e instanceof URIError)  // true
  console.log(e.message)              // URI malformed
  console.log(e.name)                 // URIError
  console.log(e.stack)                // URIError: URI malformed...
}
複製代碼

顯式拋出URIError

try {
  throw new URIError('URIError Occurred')
} 
catch (e) {
  console.log(e instanceof URIError)  // true
  console.log(e.message)        // URIError Occurred
  console.log(e.name)           // "URIError"
  console.log(e.stack)          // URIError: URIError Occurred....
}
複製代碼

瀏覽器兼容性


代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

原文:help.dottoro.com/ljfhismo.ph…


交流

文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub github.com/qq449245884… 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。

相關文章
相關標籤/搜索