Devlog

Catch errors in Promise

When using the static resolve() Promise method, you often see code like this:

Promise.resolve(func()).then(function(result) {
  console.log("Ok for: " + result);
}).catch(function(error) {
  console.log("Error: " + error);
});

console.log("Some code running after Promise.resolve...");

Everything is ok when the func() function has no errors:

function func() {
  return "OK!";
}

Output:

Some code running after Promise.resolve...
Ok for: OK!

But what when you want to return an error, like throwing one?

function func() {
  throw "Some error!";
}

Output:

Uncaught Some error!

So this is just an uncaught error that has not been catched anywhere. Also note that that code after the Promise.resolve() did not run either.

Instead of throwing an error, you could solve this by returning a rejected Promise:

function func() {
  return Promise.reject("Some error!");
}

Now the output will be:

Some code running after Promise.resolve...
Error: Some error!

So this time the error gets caught by the catch() Promise method. There is one downside to this: if the function func() is not in your hands, but is given by the user of your code, this means this user has to know it has to return a rejected Promise instead of throwing an error. To solve this, we need to add an intermediate step between the func() call and the resolve() call:

Promise.resolve((function() {
  try {
    return func();
  } catch (ex) {
    return Promise.reject(ex);
  }
}())).then(function(result) {
  console.log("Ok for: " + result.toString());
}).catch(function(error) {
  console.log("Error: " + error.toString());
});

Everything still works as before, but you can also throw errors from within func():

function func() {
  throw "Some error!";
}

Output:

Some code running after Promise.resolve...
Error: Some error!