Book Image

Mastering JavaScript Promises

Book Image

Mastering JavaScript Promises

Overview of this book

Table of Contents (16 chapters)
Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Error handling


The best part of using promise is that the error handling and debugging becomes simpler. By simply adding a few functions, you can not only pin point the location of an error in your code, but also get the relevant error log either on the console or on the browser. You don't have to add alert() all the time to investigate the nature and location of the error.

The same goes for our previous code, in which we can add an error function inside then(). Remember in the previous code where when an error occurred, no error was shown? However, not this time. We will add an error handler, which will change the background color of success to red if any error was found:

function changeHandler(e) {
  var input = e.target;
  var resDiv = document.getElementById("ResultDiv");

  WinJS.xhr({url: e.target.value}).then(
    function fulfilled (result) {
      if (result.status === 200) {
        resDiv.style.backgroundColor = "lightGreen";
        resDiv.innerText = "Successfully returned the...