你需要知道的,try..catch 不能捕獲的那些錯誤
今天的內容中,我們來學習一下使用try、catch、finally和throw進行錯誤處理。我們還會講一下 JS 中內置的錯誤對象(Error, SyntaxError, ReferenceError等)以及如何定義自定義錯誤。
1.使用 try..catch..finally..throw
在 JS 中處理錯誤,我們主要使用try、catch、finally和throw關鍵字。
try塊包含我們需要檢查的代碼關鍵字
throw用于拋出自定義錯誤catch塊處理捕獲的錯誤finally塊是最終結果無論如何,都會執(zhí)行的一個塊,可以在這個塊里面做一些需要善后的事情
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塊一起使用,它可以優(yōu)雅地處理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("這里不會被執(zhí)行");
}
? ? Uncaught SyntaxError: Invalid or unexpected token
1.2.2 try..catch 與 異步代碼
同樣,try..catch無法捕獲在異步代碼中引發(fā)的異常,例如setTimeout:
try {
setTimeout(function() {
noSuchVariable; // undefined variable
}, 1000);
} catch (err) {
console.log("這里不會被執(zhí)行");
}
未捕獲的ReferenceError將在1秒后引發(fā):
? ? 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 塊,看看下面會發(fā)生什么:
try {
throw new Error('Error while executing the code');
} finally {
console.log('finally');
}
finally
? ? Uncaught Error: Error while executing the code
這里注意兩件事:
即使從
try塊拋出錯誤后,也會執(zhí)行finally塊如果沒有
catch塊,錯誤將不能被優(yōu)雅地處理,從而導致未捕獲的錯誤
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塊中拋出錯誤后往后的代碼不會被執(zhí)行了即使在 try塊拋出錯誤之后,finally塊仍然執(zhí)行
finally塊通常用于清理資源或關閉流,如下所示:
try {
openFile(file);
readFile(file);
} catch (err) {
console.error(err.message);
} finally {
closeFile(file);
}
1.5 throw
throw語句用于引發(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. 異步代碼中的錯誤處理
對于異步代碼的錯誤處理可以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); // 這里不會被執(zhí)行
})
.then(res => {
// 這里也不會執(zhí)行,因為錯誤還沒有被處理
console.log(res);
})
.catch(err => {
console.error(err.message); // 打印 'something went wrong'
return Promise.resolve(3);
})
.then(res => {
console.log(res); // 打印 '3'
})
.catch(err => {
// 這里不會被執(zhí)行
console.error(err);
})
我們來看一個更實際的示例,其中我們使用fetch調用API,該 API 返回一個promise對象,我們使用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調用API,該API返回一個promise對象, 我們使用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 中的內置錯誤
3.1 Error
JavaScript 有內置的錯誤對象,它通常由try塊拋出,并在catch塊中捕獲,Error 對象包含以下屬性:
name:是錯誤的名稱,例如 “Error”, “SyntaxError”, “ReferenceError” 等。
message:有關錯誤詳細信息的消息。
stack:是用于調試目的的錯誤的堆棧跟蹤。
我們創(chuàng)建一個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()函數(shù)的錯誤,這個異常不再由 JS 拋出,它的存在是為了向后兼容。
3.3 RangeError
當值超出范圍時,將引發(fā)RangeError。
? [].length = -1
? Uncaught RangeError: Invalid array length
3.4 ReferenceError
當引用一個不存在的變量時,將引發(fā) ReferenceError。
? x = x + 1;
? Uncaught ReferenceError: x is not defined
3.5 SyntaxError
當你在 JS 代碼中使用任何錯誤的語法時,都會引發(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
如果該值不是預期的類型,則拋出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
最后
如果你覺得這篇內容對你挺有啟發(fā),我想邀請你幫我三個小忙:
點個「在看」,讓更多的人也能看到這篇內容(喜歡不點在看,都是耍流氓 -_-)
歡迎加我微信「 sherlocked_93 」拉你進技術群,長期交流學習...
關注公眾號「前端下午茶」,持續(xù)為你推送精選好文,也可以加我為好友,隨時聊騷。

