JS Coding Questions Logo
JS Coding Questions
#411💼 Interview💻 Code

How do you prevent promises swallowing errors

Advertisement

728x90

While using asynchronous code, JavaScript’s ES6 promises can make your life a lot easier without having callback pyramids and error handling on every second line. But Promises have some pitfalls and the biggest one is swallowing errors by default.

Let's say you expect to print an error to the console for all the below cases,

javascript
1Promise.resolve("promised value").then(function () {
2
3throw new Error("error");
4});
5
6Promise.reject("error value").catch(function () {
7
8throw new Error("error");
9});
10
11new Promise(function (resolve, reject) {
12
13throw new Error("error");
14});

But there are many modern JavaScript environments that won't print any errors. You can fix this problem in different ways,

1. Add catch block at the end of each chain: You can add catch block to the end of each of your promise chains

javascript
1Promise.resolve("promised value")
2  .then(function () {
3  throw new Error("error");
4  })
5  .catch(function (error) {
6  console.error(error.stack);
7  });

But it is quite difficult to type for each promise chain and verbose too.

2. Add done method: You can replace first solution's then and catch blocks with done method

javascript
1Promise.resolve("promised value").done(function () {
2  throw new Error("error");
3  });

Let's say you want to fetch data using HTTP and later perform processing on the resulting data asynchronously. You can write done block as below,

javascript
1getDataFromHttp()
2  .then(function (result) {
3  return processDataAsync(result);
4  })
5  .done(function (processed) {
6  displayData(processed);
7  });

In future, if the processing library API changed to synchronous then you can remove done block as below,

javascript
1getDataFromHttp().then(function (result) {
2  return displayData(processDataAsync(result));
3  });

and then you forgot to add done block to then block leads to silent errors.

3. Extend ES6 Promises by Bluebird:

Bluebird extends the ES6 Promises API to avoid the issue in the second solution. This library has a “default” onRejection handler which will print all errors from rejected Promises to stderr. After installation, you can process unhandled rejections

javascript
1Promise.onPossiblyUnhandledRejection(function (error) {
2  throw error;
3  });

and discard a rejection, just handle it with an empty catch

javascript
1Promise.reject("error value").catch(function () {});

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 68

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
411of476