简体   繁体   中英

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. 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.

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:

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.

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. But if you were actually doing the throw , you could just call reject directly:

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:

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM