cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

            
                  <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>
            
          
!
            
              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
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console