如何在 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