[英]How to catch error from Asynchronous code
The following line of code is able to catch the error (as it is sync) 以下代码行能够捕获错误(因为它是同步的)
new Promise(function(resolve, reject) {
throw new Error("Whoops!");
}).catch(alert);
But when I modify my code like below 但是,当我修改我的代码时,如下所示
new Promise(function(resolve, reject) {
setTimeout(() => {
throw new Error("Whoops!");
}, 1000);
}).catch(alert);
It is not able to catch the error. 它无法捕获错误。 I have a use case where I want to catch this error.
我有一个用例,我想抓住这个错误。 How can I achieve it?
我怎样才能实现它?
Following the link " https://bytearcher.com/articles/why-asynchronous-exceptions-are-uncatchable/ " I am able to understand why is it happening. 点击链接“ https://bytearcher.com/articles/why-asynchronous-exceptions-are-uncatchable/ ”,我就能理解为什么会这样。 Just want to know is there still any solution to catch such an error.
只是想知道是否还有任何解决方案来捕获这样的错误。
Kindly note, By the use of setTimeout, I am pointing the use of async call which can give some response or can give error as in my case when I supply incorrect URL in a fetch statement. 请注意,通过使用setTimeout,我指的是异步调用的使用,它可以给出一些响应,或者在我在fetch语句中提供不正确的URL时会出现错误。
fetch('api.github.com/users1') //'api.github.com/user'is correct url
.then(res => res.json())
.then(data => console.log(data))
.catch(alert);
You'll need a try
/ catch
inside the function you're asking setTimeout
to call: 你需要一个
try
/ catch
你问里面的功能setTimeout
调用:
new Promise(function(resolve, reject) {
setTimeout(() => {
try {
throw new Error("Whoops!"); // Some operation that may throw
} catch (e) {
reject(e);
}
}, 1000);
}).catch(alert);
The function setTimeout
calls is called completely independently of the promise executor function's execution context. 函数
setTimeout
调用完全独立于promise执行器函数的执行上下文。
In the above I've assumed that the throw new Error("Whoops!")
is a stand-in for an operation that may throw an error, rather than an actual throw
statement. 在上面我假设
throw new Error("Whoops!")
是可能抛出错误的操作的替身,而不是实际的throw
语句。 But if you were actually doing the throw
, you could just call reject
directly: 但是,如果你真的在
throw
,你可以直接调用reject
:
new Promise(function(resolve, reject) {
setTimeout(() => {
reject(new Error("Whoops!"));
}, 1000);
}).catch(alert);
Use reject to throw the error, 使用拒绝抛出错误,
new Promise(function(resolve, reject) {
setTimeout(() => {
reject(new Error("Whoops!"))
}, 1000);
}).catch(alert);
To handle errors, put the try-catch inside the setTimeout handler: 要处理错误,请将try-catch放在setTimeout处理程序中:
new Promise(function(resolve, reject) {
setTimeout(() => {
try{
throw new Error("Whoops!");
}catch(alert){
console.log(alert);
}
}, 1000);
});
You could also use a little utility: 你也可以用一点实用工具:
function timeout(delay){
return new Promise(resolve => setTimeout(resolve, delay));
}
timeout(1000)
.then(() => {
throw new Error("Whoops!");
})
.catch(alert);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.