Try..Catch 不能捕獲的錯(cuò)誤有哪些?注意事項(xiàng)又有哪些?
本文已經(jīng)原作者 Ashish Lahoti 授權(quán)翻譯。
今天的內(nèi)容中,我們來(lái)學(xué)習(xí)一下使用try、catch、finally和throw進(jìn)行錯(cuò)誤處理。我們還會(huì)講一下 JS 中內(nèi)置的錯(cuò)誤對(duì)象(Error, SyntaxError, ReferenceError等)以及如何定義自定義錯(cuò)誤。
1.使用 try..catch..finally..throw
在 JS 中處理錯(cuò)誤,我們主要使用try、catch、finally和throw關(guān)鍵字。
- try塊包含我們需要檢查的代碼
- 關(guān)鍵字throw用于拋出自定義錯(cuò)誤
- catch塊處理捕獲的錯(cuò)誤
- finally 塊是最終結(jié)果無(wú)論如何,都會(huì)執(zhí)行的一個(gè)塊,可以在這個(gè)塊里面做一些需要善后的事情
1.1 try
每個(gè)try塊必須與至少一個(gè)catch或finally塊,否則會(huì)拋出SyntaxError錯(cuò)誤。
我們單獨(dú)使用try塊進(jìn)行驗(yàn)證:
- try {
- throw new Error('Error while executing the code');
- }
- ⓧ Uncaught SyntaxError: Missing catch or finally after try
1.2 try..catch
建議將try與catch塊一起使用,它可以優(yōu)雅地處理try塊拋出的錯(cuò)誤。
- 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 與 無(wú)效代碼
try..catch 無(wú)法捕獲無(wú)效的 JS 代碼,例如try塊中的以下代碼在語(yǔ)法上是錯(cuò)誤的,但它不會(huì)被catch塊捕獲。
- try {
- ~!$%^&*
- } catch(err) {
- console.log("這里不會(huì)被執(zhí)行");
- }
- ➤ ⓧ Uncaught SyntaxError: Invalid or unexpected token
1.2.2 try..catch 與 異步代碼
同樣,try..catch無(wú)法捕獲在異步代碼中引發(fā)的異常,例如setTimeout:
- try {
- setTimeout(function() {
- noSuchVariable; // undefined variable
- }, 1000);
- } catch (err) {
- console.log("這里不會(huì)被執(zhí)行");
- }
未捕獲的ReferenceError將在1秒后引發(fā):
- ➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined
所以 ,我們應(yīng)該在異步代碼內(nèi)部使用 try..catch 來(lái)處理錯(cuò)誤:
- setTimeout(function() {
- try {
- noSuchVariable;
- } catch(err) {
- console.log("error is caught here!");
- }
- }, 1000);
1.2.3 嵌套 try..catch
我們還可以使用嵌套的try和catch塊向上拋出錯(cuò)誤,如下所示:
- 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 而沒(méi)有 catch 塊,看看下面會(huì)發(fā)生什么:
- try {
- throw new Error('Error while executing the code');
- } finally {
- console.log('finally');
- }
- finally
- ➤ ⓧ Uncaught Error: Error while executing the code
這里注意兩件事:
- 即使從try塊拋出錯(cuò)誤后,也會(huì)執(zhí)行finally塊
- 如果沒(méi)有catch塊,錯(cuò)誤將不能被優(yōu)雅地處理,從而導(dǎo)致未捕獲的錯(cuò)誤
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塊中拋出錯(cuò)誤后往后的代碼不會(huì)被執(zhí)行了
- 即使在try塊拋出錯(cuò)誤之后,finally塊仍然執(zhí)行
finally塊通常用于清理資源或關(guān)閉流,如下所示:
- try {
- openFile(file);
- readFile(file);
- } catch (err) {
- console.error(err.message);
- } finally {
- closeFile(file);
- }
1.5 throw
throw語(yǔ)句用于引發(fā)異常。
- 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. 異步代碼中的錯(cuò)誤處理
對(duì)于異步代碼的錯(cuò)誤處理可以Promise和async await。
2.1 Promise 中的 then..catch
我們可以使用then()和catch()鏈接多個(gè) Promises,以處理鏈中單個(gè) Promise 的錯(cuò)誤,如下所示:
- Promise.resolve(1)
- .then(res => {
- console.log(res); // 打印 '1'
- throw new Error('something went wrong'); // throw error
- return Promise.resolve(2); // 這里不會(huì)被執(zhí)行
- })
- .then(res => {
- // 這里也不會(huì)執(zhí)行,因?yàn)殄e(cuò)誤還沒(méi)有被處理
- console.log(res);
- })
- .catch(err => {
- console.error(err.message); // 打印 'something went wrong'
- return Promise.resolve(3);
- })
- .then(res => {
- console.log(res); // 打印 '3'
- })
- .catch(err => {
- // 這里不會(huì)被執(zhí)行
- console.error(err);
- })
我們來(lái)看一個(gè)更實(shí)際的示例,其中我們使用fetch調(diào)用API,該 API 返回一個(gè)promise對(duì)象,我們使用catch塊優(yōu)雅地處理 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調(diào)用API,該API返回一個(gè)promise對(duì)象, 我們使用try..catch塊優(yōu)雅地處理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 中的內(nèi)置錯(cuò)誤
3.1 Error
JavaScript 有內(nèi)置的錯(cuò)誤對(duì)象,它通常由try塊拋出,并在catch塊中捕獲,Error 對(duì)象包含以下屬性:
- name:是錯(cuò)誤的名稱(chēng),例如 “Error”, “SyntaxError”, “ReferenceError” 等。
- message:有關(guān)錯(cuò)誤詳細(xì)信息的消息。
- stack:是用于調(diào)試目的的錯(cuò)誤的堆棧跟蹤。
我們創(chuàng)建一個(gè)Error 對(duì)象,并查看它的名稱(chēng)和消息屬性:
- 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 有以下內(nèi)置錯(cuò)誤,這些錯(cuò)誤是從 Error 對(duì)象繼承而來(lái)的
3.2 EvalError
EvalError 表示關(guān)于全局eval()函數(shù)的錯(cuò)誤,這個(gè)異常不再由 JS 拋出,它的存在是為了向后兼容。
3.3 RangeError
當(dāng)值超出范圍時(shí),將引發(fā)RangeError。
- ➤ [].length = -1
- ⓧ Uncaught RangeError: Invalid array length
3.4 ReferenceError
當(dāng)引用一個(gè)不存在的變量時(shí),將引發(fā) ReferenceError。
- ➤ x = x + 1;
- ⓧ Uncaught ReferenceError: x is not defined
3.5 SyntaxError
當(dāng)你在 JS 代碼中使用任何錯(cuò)誤的語(yǔ)法時(shí),都會(huì)引發(fā)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
如果該值不是預(yù)期的類(lèi)型,則拋出TypeError。
- ➤ 1();
- ⓧ Uncaught TypeError: 1 is not a function
- ➤ null.name;
- ⓧ Uncaught TypeError: Cannot read property 'name' of null
3.7 URIError
如果以錯(cuò)誤的方式使用全局 URI 方法,則會(huì)拋出URIError。
- ➤ decodeURI("%%%");
- ⓧ Uncaught URIError: URI malformed
4. 定義并拋出自定義錯(cuò)誤我們也可以用這種方式定義自定義錯(cuò)誤。
- 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
我們還可以進(jìn)一步增強(qiáng)CustomError對(duì)象以包含錯(cuò)誤代碼
- 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
本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。