3

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

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Use reject to throw the error,

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.