如何在 JavaScript 的非同步生成器函式中丟擲錯誤?
程式碼經常丟擲錯誤,處理錯誤非常重要。JavaScript 也允許使用者使用“throw”關鍵字丟擲自定義錯誤。我們可以在 catch 程式碼塊中捕獲這些錯誤。
我們可以使用 try-catch 語法來捕獲普通函式丟擲的錯誤。讓我們透過下面的示例來理解它。
示例 1(在普通函式中丟擲錯誤)
在下面的示例中,我們建立了 throwError() 普通函式,它使用 throw 關鍵字丟擲帶有自定義錯誤訊息的錯誤。我們在 try 程式碼塊中執行了該函式。如果函式丟擲任何錯誤,控制權將轉移到 catch 程式碼塊,這就是我們如何檢測錯誤的方式。
<html>
<body>
<h3> Using the throw keyword to throw an error from the normal function </h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// throw error from normal function
function throwError() {
throw new Error('Error from normal function');
}
try {
throwError();
} catch (e) {
content.innerHTML = e;
}
</script>
</body>
</html>
如果我們將 throwError() 函式設為非同步函式,它將生成另一個錯誤,因為我們可以使用 try-catch 程式碼塊處理同步函式丟擲的錯誤。
為了解決這個問題,使用者必須使用 then-catch 程式碼塊語法來解決 Promise。
語法
使用者可以按照以下語法來解決非同步函式丟擲的錯誤。
throwError().then((res) => {
// print content
}).catch((err) => {
// print error message
})
在上述語法中,throwError() 是一個返回 Promise 的函式,我們使用 then 和 catch 程式碼塊來解決它。
示例 2(從非同步函式丟擲錯誤)
在下面的示例中,throwError() 函式是一個非同步函式,因為我們在函式關鍵字之前添加了“async”關鍵字。我們從非同步函式中丟擲錯誤的方式與從普通函式中丟擲錯誤的方式相同。
之後,我們使用 then 和 catch 程式碼塊處理了 Promise。在輸出中,使用者可以觀察到,由於非同步函式丟擲了錯誤,控制權轉移到了 catch 程式碼塊。
<html>
<body>
<h3> Using the <i> throw </i> keyword to throw an error from the async function </h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// throw error from normal function
async function throwError() {
throw new Error('Error from Async function');
}
throwError().then((res) => {
content.innerHTML = res;
}).catch((err) => {
content.innerHTML = err;
})
</script>
</body>
</html>
示例 3(透過在非同步函式中拒絕 Promise 來丟擲錯誤)
我們可以從非同步函式中返回 Promise。非同步函式中的拒絕 Promise 就像丟擲錯誤一樣。我們在回撥函式中使用了 reject() 方法來拒絕 Promise。
“then-catch”程式碼塊用於解決函式返回的 Promise,使用者可以看到控制權轉移到了 catch 程式碼塊。
<html>
<body>
<h3> Using the <i> reject </i> method to throw an error from the async function </h3>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
// throw error from normal function
async function throwError() {
return new Promise((resolve, reject) => {
reject("This promise is rejected from the async function." );
});
}
throwError().then((res) => {
content.innerHTML = res;
}).catch((err) => {
content.innerHTML = err;
})
</script>
</body>
</html>
使用者學習瞭如何從非同步函式中丟擲錯誤。使用者可以使用“throw”關鍵字(就像普通函式一樣)來丟擲錯誤。使用者需要使用“then-catch”程式碼塊來處理錯誤,因為非同步函式返回 Promise,而不是使用 try-catch 程式碼塊來處理。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP