Error Logging

(Pure JS) Compilation of debugging techniques wrapped into a single example

by Don Schaefer

JavaScript

var name = prompt('What is your name?');
var date = new Date();
var time = date.getHours(); 
var greeting = 'Good evening ';
var punctuation = '!';

function logData(f){
    //Group all relevant data into a single collapsable entry in the console. Note that the group is encapsulated by console.group() & console.groupEnd() commands rather than simply  'console.group(){' & '}' 
    console.group('Collected Data');
        console.log('Function: '+f); //Name of the function that triggered this command
        console.info('Name: '+name);
        console.warn('Military Time: '+time);  
        console.assert(time > 6, 'You have awoken the beast!'); //Message to display if assertion returns false
    console.groupEnd();
}

function formulateGreeting(){
    if(time < 18){
        if(time < 12){
            if(time < 6){
                greeting = 'Can\'t you see I\'m trying to sleep';
                punctuation = '?'
            }else{
                greeting = 'Good morning';
            }
        }else{
            greeting = 'Good afternoon';
        }
    }
    debugger; //Set breakpoint in browser so that the console (if it is open) will pause the script & allow you to check the values of all variables
    try { //First try to run this code                
        if(isNaN(time*name)){
            alert(greeting + name + punctuation);
        }else{
            throw new Error('visitor entered an invalid name');
        }
    }catch(e){ //If there's a problem, run this code
        console.error('Error: '+e.message);
    }finally{ //Always run this code
        logData('formulateGreeting');
    }
}

formulateGreeting();