Error logging function for javascript
1 min read

Error logging function for javascript

While working on a javascript function, I started adding some verifications to make sure I would know what exactly went wrong in case something didn't work correctly. Like this:

function foo(variable) {
    if(typeof variable === undefined) {
        console.log('Error: variable is undefined in function foo');
   }
}

...and after a lot of such logs, I got a little annoyed. Just like last time, when I made myself another useful function for logging, I wanted to make my own.

There was also another reason: the final .js file will be most likely minified and have all the console.logs removed. While it is true that I can always use the original .js file for debugging, there are some cases where it would be nice to have some sort of logs in the live version too, to help you with some particular cases, where you can't simply switch the .js files and check the console.

So this is what I came up with:

/** logError function
 * outputs custom error messages to the console
 * parametres: message - required, the error message text (ok, it's practically optional)
 * parametres: al - optional, a bool variable for showing or not an alert, default: false
 * if "al" is set to true, the error message is also shown as a javascript alert
 */
function logError(message, al) {
	message = (typeof message === "undefined") ? "no message" : message; //defaults to 'no message'
	al = (typeof al === "undefined") ? false : al; //defaults to false
	
	var fName;
	try {
		fName = logError.caller.name;
	}catch(err) {
		fName = 'not supported on this browser'; ///fallback for older browsers	
	}
	var msg = 'Error: ' + message + ' / function: ' + fName;
	console.log(msg);
	if(al) {
		alert(msg);
	}
}

Now, my original function would be more like this:

function foo(variable) {
    if(typeof variable === undefined) {
        logError('undefined variable'); //outputs "Error: undefined variable / function foo"
        //logError('undefined variable', true); will also show an alert
   }
}

The neatest part here is the function.caller.name part, which lets me detect the function name.
I can use the error log inside foo() and get foo, then use the same logging function inside bar() to get bar.