沐鳴娛樂業務:_try..catch 不能捕獲的錯誤有哪些?注意事項又有哪些?

今天的內容中,我們來學習一下使用try、catch、finally和throw進行錯誤處理。我們還會講一下 js 中內置的錯誤對象(Error, SyntaxError, ReferenceError等)以及如何定義自定義錯誤。

1.使用 try..catch..finally..throw

在 js 中處理錯誤,我們主要使用try、catch、finally和throw關鍵字。

  • try塊包含我們需要檢查的代碼
  • 關鍵字throw用於拋出自定義錯誤
  • catch塊處理捕獲的錯誤
  • finally 塊是最終結果無論如何,都會執行的一個塊,可以在這個塊裏面做一些需要善後的事情

1.1 try

每個try塊必須與至少一個catch或finally塊,否則會拋出SyntaxError錯誤。

我們單獨使用try塊進行驗證:

try {
  throw new Error('Error while executing the code');
}
ⓧ Uncaught SyntaxError: Missing catch or finally after try

1.2 try..catch

建議將try與catch塊一起使用,它可以優雅地處理try塊拋出的錯誤。

try {
  throw new Error('Error while executing the code');
} catch (err) {
  console.error(err.message);
}
Error while executing the code

1.2.1 try..catch 與 無效代碼

try..catch 無法捕獲無效的 JS 代碼,例如try塊中的以下代碼在語法上是錯誤的,但它不會被catch塊捕獲。

try {
  ~!$%^&*
} catch(err) {
  console.log("這裏不會被執行");
}
  Uncaught SyntaxError: Invalid or unexpected token

1.2.2 try..catch 與 異步代碼

同樣,try..catch無法捕獲在異步代碼中引發的異常,例如setTimeout:

try {
  setTimeout(function() {
    noSuchvariable;   // undefined variable
  }, 1000);
} catch (err) {
  console.log("這裏不會被執行");
}

未捕獲的ReferenceError將在1秒后引發:

Uncaught ReferenceError: noSuchVariable is not defined

所以 ,我們應該在異步代碼內部使用 try..catch 來處理錯誤:

setTimeout(function() {
  try {
    noSuchVariable;
  } catch(err) {
    console.log("error is caught here!");
  }
}, 1000);

1.2.3 嵌套 try..catch

我們還可以使用嵌套的try和catch塊向上拋出錯誤,如下所示:

try {
  try {
    throw new Error('Error while executing the inner code');
  } catch (err) {
    throw err;
  }
} catch (err) {
  console.log("Error caught by outer block:");
  console.error(err.message);
}
Error caught by outer block:
 ⓧ Error while executing the code

1.3 try..finally

不建議僅使用 try..finally 而沒有 catch 塊,看看下面會發生什麼:

try {
  throw new Error('Error while executing the code');
} finally {
  console.log('finally');
}
finally
 ⓧ Uncaught Error: Error while executing the code

這裏注意兩件事:

  • 即使從try塊拋出錯誤后,也會執行finally塊
  • 如果沒有catch塊,錯誤將不能被優雅地處理,從而導致未捕獲的錯誤

1.4 try..catch..finally

建議使用try…catch塊和可選的finally塊。

try {
  console.log("Start of try block");
  throw new Error('Error while executing the code');
  console.log("End of try block -- never reached");
} catch (err) {
  console.error(err.message);
} finally {
  console.log('Finally block always run');
}
console.log("Code execution outside try-catch-finally block continue..");
Start of try block
 ⓧ Error while executing the code
Finally block always run
Code execution outside try-catch-finally block continue..

這裏還要注意兩件事:

  • 在try塊中拋出錯誤后往後的代碼不會被執行了
  • 即使在try塊拋出錯誤之後,finally塊仍然執行

finally塊通常用於清理資源或關閉流,如下所示:

try {
  openFile(file);
  readFile(file);
} catch (err) {
  console.error(err.message);
} finally {
  closeFile(file);
}

1.5 throw

throw語句用於引發異常。

throw <expression>
// throw primitives and functions
throw "Error404";
throw 42;
throw true;
throw {toString: function() { return "I'm an object!"; } };

// throw error object
throw new Error('Error while executing the code');
throw new SyntaxError('Something is wrong with the syntax');
throw new ReferenceError('Oops..Wrong reference');

// throw custom error object
function ValidationError(message) {
  this.message = message;
  this.name = 'ValidationError';
}
throw new ValidationError('Value too high');

2. 異步代碼中的錯誤處理

對於異步代碼的錯誤處理可以Promise和async await。

2.1 Promise 中的 then..catch

我們可以使用then()和catch()鏈接多個 Promises,以處理鏈中單個 Promise 的錯誤,如下所示:

Promise.resolve(1)
  .then(res => {
      console.log(res);  // 打印 '1'

      throw new Error('something went wrong');  // throw error

      return Promise.resolve(2);  // 這裏不會被執行
  })
  .then(res => {
      // 這裏也不會執行,因為錯誤還沒有被處理
      console.log(res);    
  })
  .catch(err => {
      console.error(err.message);  // 打印 'something went wrong'
      return Promise.resolve(3);
  })
  .then(res => {
      console.log(res);  // 打印 '3'
  })
  .catch(err => {
      // 這裏不會被執行
      console.error(err);
  })

我們來看一個更實際的示例,其中我們使用fetch調用API,該 API 返回一個promise對象,我們使用catch塊優雅地處理 API 失敗。

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok"))
    .catch(error => console.log("Caught", error));
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)

2.2 try..catch 和 async await

在 async await 中 使用 try..catch 比較容易:

(async function() {
    try {
        await fetch("http://httpstat.us/500");
    } catch (err) {
        console.error(err.message);
    }
})();

讓我們看同一示例,其中我們使用fetch調用API,該API返回一個promise對象, 我們使用try..catch塊優雅地處理API失敗。

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
}

(async function() {
    try {
      let response = await fetch("http://httpstat.us/500");
      handleErrors(response);
      let data = await response.json();
      return data;
    } catch (error) {
        console.log("Caught", error)
    }
})();
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)
    at <anonymous>:11:7

3. JS 中的內置錯誤

3.1 Error

JavaScript 有內置的錯誤對象,它通常由try塊拋出,並在catch塊中捕獲,Error 對象包含以下屬性:

  • name:是錯誤的名稱,例如 “Error”, “SyntaxError”, “ReferenceError” 等。
  • message:有關錯誤詳細信息的消息。
  • stack:是用於調試目的的錯誤的堆棧跟蹤。

我們創建一個Error 對象,並查看它的名稱和消息屬性:

const err = new Error('Error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
console.log("stack:", err.stack);
name: Error
message: Error while executing the code
stack: Error: Error while executing the code
    at <anonymous>:1:13

JavaScript 有以下內置錯誤,這些錯誤是從 Error 對象繼承而來的

3.2 EvalError

EvalError 表示關於全局eval()函數的錯誤,這個異常不再由 JS 拋出,它的存在是為了向後兼容。

3.3 RangeError

當值超出範圍時,將引發RangeError。

 [].length = -1
ⓧ Uncaught RangeError: Invalid array length

3.4 ReferenceError

當引用一個不存在的變量時,將引發 ReferenceError

 x = x + 1;
 Uncaught ReferenceError: x is not defined

3.5 SyntaxError

當你在 JS 代碼中使用任何錯誤的語法時,都會引發SyntaxError。

 function() { return 'Hi!' }
ⓧ Uncaught SyntaxError: Function statements require a function name  1 = 1 ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment  JSON.parse("{ x }"); ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2

3.6 TypeError

如果該值不是預期的類型,則拋出TypeError。

 1();
 Uncaught TypeError: 1 is not a function

 null.name;
 Uncaught TypeError: Cannot read property 'name' of null

3.7 URIError

如果以錯誤的方式使用全局 URI 方法,則會拋出URIError。

 decodeURI("%%%");
ⓧ Uncaught URIError: URI malformed

4. 定義並拋出自定義錯誤

我們也可以用這種方式定義自定義錯誤。

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  } 
};

const err = new CustomError('Custom error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
name: CustomError
message: Custom error while executing the code

我們還可以進一步增強CustomError對象以包含錯誤代碼

class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.name = "CustomError";
    this.code = code;
  } 
};

const err = new CustomError('Custom error while executing the code', "ERROR_CODE");

console.log("name:", err.name);
console.log("message:", err.message);
console.log("code:", err.code);
name: CustomError
message: Custom error while executing the code
code: ERROR_CODE

在try..catch塊中使用它:

try{
  try {
    null.name;
  }catch(err){
    throw new CustomError(err.message, err.name);  //message, code
  }
}catch(err){
  console.log(err.name, err.code, err.message);
}

CustomError TypeError Cannot read property ‘name’ of null

原文:https://codings.com/

站長推薦

1.雲服務推薦: 國內主流雲服務商,各類雲產品的最新活動,優惠券領取。地址:阿里雲騰訊雲華為雲

2.廣告聯盟: 整理了目前主流的廣告聯盟平台,如果你有流量,可以作為參考選擇適合你的平台點擊進入

鏈接: http://www.fly63.com/article/detial/10054