Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                    <head>
        <title>Testing Error Handling with JavaScript Promises </title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="./testIt.js"></script>
    </head>
    <body>
        <h4>Testing JavaScript Promises</h4>
        <button onclick="testMe1()">Working Sample</button> 
        <button onclick="testMe2()">Invalid URL</button> 
        <button onclick="testMe3()">Data Error</button> 
        <button onclick="testMe4()">Fix Invalid URL</button> 
        <button onclick="testMe5()">Fix Data Error</button> 
        <button onclick="clearDisplay()">Clear Display</button> 
        <div id="Display"></div>
    </body>
              
            
!

CSS

              
                
              
            
!

JS

              
                document.onreadystatechange = function () {
  if (document.readyState === "complete") {
     testMe1();
    }
};

/*
   Note: https://cors-anywhere.herokuapp.com PREFIX is used to fix Mixed Content
   issues - as Codepen runs on HTTPS  https://codepen.io
   
*/
function testMe1() {
    testMe("https://cors-anywhere.herokuapp.com/" + "http://hhutzler.de/myID.php", "Working Sample", false); 
}

function testMe2() {
    testMe("http://hhutzler/myID.php", "Invalid URL",false); 
}
function testMe3() {
    testMe("http://hhutzler.de/myID.php", "Mimicking a Data Processing Error",true);
}
function testMe4() {
    testMeFix("http://hhutzler./myID.php", "Invalid URL",false);
}
function testMe5() {
    testMeFix("http://hhutzler.de/myID.php", "Mimicking a Data Processing Error",true);
}

function testMe(myUrl, test, dataError) {
    dumpMessage("Testing Promise Chaining: "  + test, false);
    let url = myUrl;
    fetch(url)                           // fetch returns a promise       
        .then(response => {              // Our Success Handler returns response Object 
            if(response.ok) {
                if ( dataError) {        // Just for testing - Mimicking a Data Proessing Error
                    throw new Error('Data Processing Error');
                }  
                return response.json();
            }
            throw new Error('Network response was not ok  at Chain Level 1');
        })  // Catches Exception for our Success Handler and for our Reject Handler 
    .catch(e => { 
        dumpMessage("Exception at Chain Level 1  : " + e,true );  
        throw new Error('Initial Fetch failed for URL: ' + url); 
    })
    .then(jsonData => { dumpMessage("ID: " + jsonData.id + " - name : " + jsonData.name,false ); return(jsonData.name);} )
    .then( (user) => {  dumpMessage("Username: " + user, false);  return fetch("https://api.github.com/users/"+user ); })
        // Load the response as json
    .then(response => response.json())     
        // Show the avatar image (githubUser.avatar_url) for 3 seconds (maybe animate it)
    .then(githubUser => {
        dumpMessage("Displaying Github Avatar Image for 3 seconds!", false);  
        let img = document.createElement('img');
        img.src = githubUser.avatar_url;
        img.className = "promise-avatar-example";
        document.body.append(img);

        setTimeout(() => {
            img.remove();
            dumpMessage("Removed Github Avatar Image !", false);
        }, 3000); // (*)
    })
    .catch(err => {             // Catch all Hanlder return true/false for retry logic 
        dumpMessage("CatchAll Error-handler: " + err, true);
        });
} 

function testMeFix(myUrl, test, dataError) {
    dumpMessage("Testing Promise Chaning and Error Handling: "  + test, false);
    let url = myUrl;
    fetch(url)                      
        .then(response => {              // Our Success Handler 
            if(response.ok) {
                if ( dataError) {        // Mimicking a Data Proessing Error
                    throw new Error('Data Processing Error');
                }  
                return response.json();
            }
            throw new Error('Network response was not ok.');
        },      
        err => {    // Now we handle the error (rejection reason)
            dumpMessage("Handle error (rejection reason): " + err,true );  
               // Create a Dummy object
            dumpMessage("Create a Default Object to Finish Promise Chain");    
            myObj = { "name":"hhutzler", "id":999 };
            return myObj;
        } )
        .catch(e => { dumpMessage("Processing Error Chaining at Level 1  : " + e,true );  
            dumpMessage("Create a Default Object to Finish Promise Chain");    
            myObj = { "name":"hhutzler", "id":999 };
            return myObj;                   
        })
            //        ,        // Now we handle the error (rejection reason)
            //e => { dumpMessage("Initial Fetch Error: " + e,true );  throw new Error('Initial Fetch Error for URL' + url); } )
            //.then(response =>  response.json() )
    .then(jsonData => { dumpMessage("ID: " + jsonData.id + " - name : " + jsonData.name,false ); return(jsonData.name);} )
    .then( (user) => {  dumpMessage("Username: " + user, false);  return fetch("https://api.github.com/users/"+user ); })
        // Load the response as json
    .then(response => response.json())
        // Show the avatar image (githubUser.avatar_url) for 3 seconds (maybe animate it)
    .then(githubUser => {
        dumpMessage("Displaying Github Avatar Image for 3 seconds!", false);  
        let img = document.createElement('img');
        img.src = githubUser.avatar_url;
        img.className = "promise-avatar-example";
        document.body.append(img);

        setTimeout(() => {
            img.remove();
            dumpMessage("Removed Github Avatar Image !", false);
        }, 3000); // (*)
    })
    .catch(err => dumpMessage("CatchAll Error-handler: " + err  , true));
}

      // Helper Functions 							
function dumpMessage( mesg, isError) {
    let color = "blue";
    if (isError) {
        color = "red";
    }
   
    let message = getTime() + ":: --> " + mesg;
    let logElem =  document.getElementById("Display");
    if (logElem) {
        let logBuffer = logElem.innerHTML;
        logElem.innerHTML=logBuffer + "<pre> <span style=color:" + color + ">" + message + " </span> </pre>";
        logElem.scrollTop = logElem.scrollHeight;   // AutoScroll Logger Window to show latest Messages
    }
    console.log(message);                                 	
}

function clearDisplay() {
    let logElem =  document.getElementById("Display");
    if (logElem) {
        logElem.innerHTML="";
    }                               	
}

function getTime() {
    let ts = new Date();
    return ts.toLocaleTimeString()+ ":" + ts.getMilliseconds() + "  ";   
}
              
            
!
999px

Console