Amit Sharma
Amit Sharma

Reputation: 31

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

Upvotes: 3

Views: 69

Answers (4)

Thomas
Thomas

Reputation: 12637

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

Upvotes: 0

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

Use reject to throw the error,

new Promise(function(resolve, reject) {
  setTimeout(() => {
    reject(new Error("Whoops!"))
  }, 1000);
}).catch(alert);

Upvotes: 2

Osama
Osama

Reputation: 3040

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074258

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

Upvotes: 2

Related Questions