Error handling with Promises

by Konstantin Rouda

HTML

<button>Fetch DATA</button>

<div>

</div>

CSS

HTML {
  font-size: 18px;
  line-height: 1.5;
  box-sizing: content-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

BUTTON {
  margin: 1em 0 1em 5em;
}

DIV {
  max-width: 40em;
  margin: 2em auto 0;
  padding: 1em;
  border: 1px solid #0bf;
}

.error {
  color: red;
}

JavaScript

(function () {
	"use strict";
  


		var btn = document.querySelector("button");
		var div = document.querySelector("div");
    
btn.addEventListener("click", function (e) {
    
    var urlPromise = fetchURL("https://jsonplaceholder.typicode.com/users5"); // url is corrupted on purpose (digit 5 was added at the end of the url)
    
    urlPromise.then(function (data) {
        debugger;
        return JSON.parse(data);
    }, function (error) {
        debugger;
        div.textContent += "Error from first then: " + error;
        div.classList.add("error");
    }).then(function (parsedData) {  
        debugger;
         
        parsedData.forEach(function (data, index) {
          div.innerHTML += "<br /><br />" + index + ") Name: " + data.name + " | Email: " + data.email;
        });
      
    });

		/// catch all handler for handling any errors that occur
    urlPromise.catch(function (error) {
        div.innerHTML += "<br /><br />Error from Promise Catch: " + error;
        div.classList.add("error");
    });
    
    
}); // END btn.AddEventListener






    /*Utility Function*/

		// Fetching data from specified URL, using XMLHttpRequest and Promise.
    function fetchURL(url) {

        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);

            xhr.addEventListener("load", function (e) {
                if (xhr.status < 400 && (xhr.statusText === "OK" || xhr.statusText === "")) {
                    resolve(xhr.response);
                } else {
                    reject(new Error("Request failed: " + xhr.statusText));
                }
            });

            xhr.addEventListener("error", function (e) {
                reject(new Error("Request failed: " + xhr.statusText));
            });

            xhr.send(null);
        });

    };
    
    
})();