JavaScript Try Catch - javascript

I'm looking at some code on a website that hides / shows content on a click.
function expando() {
try {
if (document.getElementsByClassName) {
var e = document.getElementsByClassName("expandlink");
t = 0;
} else {
var e = document.querySelectorAll(".expandlink"),
t = 1;
};
if (null != e) {
for (var a = 0; a < e.length; ++a) e[a].onclick = function() {
return OpenClose(this), !1
};
if (1 == t)
for (var a = 0; a < e.length; ++a) {
var n = e[a].href,
r = n.indexOf("#"),
i = n.substr(r + 1),
l = document.getElementById(i);
l.className = l.className + " expandtargetIE8"
}
}
} catch (o) {}
}
function OpenClose(e) {
try {
var t = e.href,
a = t.indexOf("#"),
n = t.substr(a + 1),
r = document.getElementById(n);
r.className = "expandtarget" === r.className ||
"expandtarget expandtargetIE8" === r.className ?
"expandtargeted" : "expandtarget expandtargetIE8",
e.className = "expandlink" === e.className ?
"expandlink expandlinked" : "expandlink"
} catch (i) {}
}
window.onload = function() {
expando()
};
Here is the JS Fiddle.
https://jsfiddle.net/amykirst/3hbxwv1d/
I've never seen the JavaScript try...catch statement. I looked at some tutorials, and they all say that they are for error testing. Why would it be used here?
It doesn't look like the catch actually does anything.
Note: this code had been minified. I used an online tool to unminify it.

The try..catch block here is used for error handling. It's used here to allow the code to continue normal execution if an error does arise.
Not all browsers will support both document.getElementsByClassName and document.querySelectorAll. On a browser which doesn't support either, we'd get the following error:
Uncaught TypeError: document.querySelectorAll is not a function
...and further code execution would stop.
However with a try..catch block here, the code instead wouldn't alert us about the error at all (at least, not without inspecting o within the catch block). Execution would continue as normal. It's no longer an uncaught error, it's a caught error which simply has nothing done with it.
If in the same browser we're to adjust the above code to log o within the catch block:
... } catch (o) { console.log(o) }
The same message shown above would be displayed on the console, without the "uncaught" part:
TypeError: document.querySelectorAll is not a function(…)

Actually there are few real use case of try-catch.
Error handling : Your JS function/statements may throw error, like TypeError (Accessing undefined,null) , JsonParseError etc. Sometimes you need that to be handled, so that next set of statements has to be executed. If it is not handled, the JS engine will throw it and halts the function execution.
Getting meaningfull information from multiple function call stack: You may get into situation, in legacy codes, that function f1 is calling f2 and f2 calling f3 and so on. You may want to do some validation check and if validation fails you may like to stop the flow and show meaningfull error message. (like saying, invalid state). To handle this kind of scenario, we can handle with Custom Exception.
function ValidationError(message) {
this.name = "IocError";
this.message = (message || "Validation/System Error");
}
ValidationError.prototype = Error.prototype;
we can throw the custom error, if we see any validation error, like throw new ValidationError('Rule is missing...') in the function f3.
try {
...
} catch(e) {
if(e instanceof ValidationError) {
infoBox(e.message);
return false;
} else {
//This is not validation error, some other unknown issue has occurred
throw e;
}
}
We will use the above block to catch the exception in function f1 and if it is of type ValidationError, we'll display proper error message. If it as any other type we'll throw back for future debug purpose.

Related

Check whether file exists in Google Drive by using trigger file IDs

I capture file ids from triggers and check whether file exists in drive by. The below script throws exception and terminates the scripts abruptly if any of the trigger associated file is missing or if it is trash as mentioned in the Apps script openById documentation (which is natural). How do I overcome this?
function getForms() {
try {
var formsList = [];
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
var fid = triggers[i].getTriggerSourceId();
if (fid) {
var title = FormApp.openById(fid).getTitle() == "" ? "Untitled" : FormApp.openById(fid).getTitle();
formsList.push([title, fid]);
}
}
return formsList;
} catch (e) {
;//catch errors
}
}
You may use the try catch statement wisely to avoid the Exception:
try {
if (fid) {
var title = FormApp.openById(fid).getTitle() == "" ? "Untitled" : FormApp.openById(fid).getTitle();
formsList.push([title, fid]);
}
} catch (e) {
Logger.log(e.message);
}
Use try catch inside for loop instead of outside in a useless place

"undefined" in exception handling while printing custom error message

Hi I am getting a "undefined" with my custom error message.Why? I only want error message.Can anyone help please.
function divide() {
let num = 2;
let den = 0;
try{
if (den == 0){
throw new Error("division invalid");
}
return Number(num/den);
} catch(e){
console.log(e.message);
}
}
console.log(divide());
Functions that don't have an explicit return, return undefined implicitly. You are throwing an error and then not returning anything in the catch block. Since you aren't returning a value, it sends undefined.
function divide() {
let num = 2;
let den = 0;
try {
if (den == 0) {
throw new Error("division invalid");
}
return Number(num/den);
} catch(e){
console.log(e.message);
return 'Can\'t divide by 0!';
}
}
console.log(divide());
Notice in this code snippet that I am returning a string in the catch. The line return Number(num/den); is never called because there was an error.
Instead of logging the error within the function, you can return it to the calling method.
function divide() {
let num = 2;
let den = 0;
try {
if (den == 0) {
throw new Error("division invalid");
}
return Number(num / den);
} catch (e) {
return e.message;
}
}
console.log(divide());
your code is working absolutely correct . I have tested this on my console.
Most probably the problem is with your console settings, currently the console must be set to show errors only. So , change the chrome console output to Verbose or All. I am attaching the snapshot of how to change the settings and the output of your code as per your expectation.
Solution to your problem Click here
For completeness: In the current version of chrome, the setting is no longer at the bottom but can be found when clicking the "Filter" icon at the top of the console tab (second icon from the left)
You can click here for further reference.
I hope this solves your problem . Thanks :)
Console.log() function returns undefined. So do what #Krypton suggests, though that will still lead to the undefined still showing up. But hey, at least it's one less undefined, no?

How to handle multiple errors thrown by an utility function?

I have a function examples(a,b,c,…). Each argument can throw an error. All of them are handled the same way. I guess examples([array]) would fall in the same category.
In my code I have something like that currently:
for (i = 0; i < len; i++) {
try { this.example(arg[i]) }
catch (e) { log(e) }
}
From an user perspective Id like to be able to see the errors of all arguments at once instead of fixing one and then discovering the next one etc. But I end up catching myself which seems, to me, not desirable for an utility function.
Is there a way to rethrow all errors at once?
What are the best practices?
If there's a standard, why is it being recommended?
Well you can throw pretty much anything, but rather than just a simple Array, you may find you have more maneuverability using a custom error type
function ErrorCollection(msg) {
this.name = 'ErrorCollection';
this.message = msg || '';
this.errors = [];
}
ErrorCollection.prototype = Object.create(Error.prototype);
ErrorCollection.prototype.constructor = ErrorCollection;
ErrorCollection.prototype.push = function (e) {
return this.errors.push(e);
}
// ...
var i, ec = new ErrorCollection();
for (i = 0; i < 10; ++i) {
try {
throw new Error('Error ' + i);
} catch (e) {
ec.push(e);
}
}
// do something with ec, e.g.
if (ec.errors.length) {
console.log(ec, ec.errors);
throw ec;
}
An example of stopping on the first error then validity checking the remainder
var i, a = [];
for (i = 0; i < arguments.length; ++i) {
try { // assume everything will work
this.example(arguments[i]);
} catch (e) { // our assumption was wrong
a.push({arg: i, val: arguments[i]});
for (++i; i < arguments.length; ++i) { // loop from where we left off
if (!this.valid_arg(arguments[i])) { // some costly test
a.push({arg: i, val: arguments[i]});
}
}
throw a; // throw the list of bad args up a level
}
}
If the validity test will be fast/isn't costly then you may consider doing it in advance of your main loop instead of waiting for the first error, as you should then be able to avoid try..catch at this level entirely.

Understanding try..catch in Javascript

I have this try and catch problem. I am trying to redirect to a different page. But sometimes it does and some times it doesnt. I think the problem is in try and catch . can someone help me understand this. Thanks
var pg = new Object();
var da = document.all;
var wo = window.opener;
pg.changeHideReasonID = function(){
if(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0){
pg.otherReason.style.backgroundColor = "ffffff";
pg.otherReason.disabled = 0;
pg.otherReason.focus();
} else {
pg.otherReason.style.backgroundColor = "f5f5f5";
pg.otherReason.disabled = 1;
}
}
pg.exit = function(pid){
try {
if(window.opener.hideRecordReload){
window.opener.hideRecordReload(pg.recordID, pg.recordTypeID);
} else {
window.opener.pg.hideRecord(pg.recordID, pg.recordTypeID);
}
} catch(e) {}
try {
window.opener.pg.hideEncounter(pg.recordID);
} catch(e) {}
try {
window.opener.pg.hideRecordResponse(pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text);
} catch(e) {}
try {
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
} catch(e) {}
try {
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
} catch(e) {}
try {
window.opener.window.parent.frames[1].pg.loadQualityMeasureRequest();
} catch(e) {}
try {
window.opener.pg.closeWindow();
} catch(e) {}
parent.loadCenter2({reportName:'redirectedpage',patientID:pid});
parent.$.fancybox.close();
}
pg.hideRecord = function(){
var pid = this.pid;
pg.otherReason.value = pg.otherReason.value.trim();
if(pg.hideReasonID.selectedIndex == 0){
alert("You have not indicated your reason for hiding this record.");
pg.hideReasonID.focus();
} else if(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0 && pg.otherReason.value.length < 2){
alert("You have indicated that you wish to enter a reason\nnot on the list, but you have not entered a reason.");
pg.otherReason.focus();
} else {
pg.workin(1);
var n = new Object();
n.noheaders = 1;
n.recordID = pg.recordID;
n.recordType = pg.recordType;
n.recordTypeID = pg.recordTypeID;
n.encounterID = request.encounterID;
n.hideReasonID = pg.hideReasonID.value;
n.hideReason = pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text;
Connect.Ajax.Post("/emr/hideRecord/act_hideRecord.php", n, pg.exit(pid));
}
}
pg.init = function(){
pg.blocker = da.blocker;
pg.hourglass = da.hourglass;
pg.content = da.pageContent;
pg.recordType = da.recordType.value;
pg.recordID = parseInt(da.recordID.value);
pg.recordTypeID = parseInt(da.recordTypeID.value);
pg.information = da.information;
pg.hideReasonID = da.hideReasonID;
pg.hideReasonID.onchange = pg.changeHideReasonID;
pg.hideReasonID.tabIndex = 1;
pg.otherReason = da.otherReason;
pg.otherReason.tabIndex = 2;
pg.otherReason.onblur = function(){
this.value = this.value.trim();
}
pg.otherReason.onfocus = function(){
this.select();
}
pg.btnCancel = da.btnCancel;
pg.btnCancel.tabIndex = 4;
pg.btnCancel.title = "Close this window";
pg.btnCancel.onclick = function(){
//window.close();
parent.$.fancybox.close();
}
pg.btnHide = da.btnHide;
pg.btnHide.tabIndex = 3;
pg.btnHide.onclick = pg.hideRecord;
pg.btnHide.title = "Hide " + pg.recordType.toLowerCase() + " record";
document.body.onselectstart = function(){
if(event.srcElement.tagName.search(/INPUT|TEXT/i)){
return false;
}
}
pg.workin(0);
}
pg.workin = function(){
var n = arguments.length ? arguments[0] : 1;
pg.content.disabled = pg.hideReasonID.disabled = n;
pg.blocker.style.display = pg.hourglass.style.display = n ? "block" : "none";
if(n){
pg.otherReason.disabled = 1;
pg.otherReason.style.backgroundColor = "f5f5f5";
} else {
pg.otherReason.disabled = !(pg.hideReasonID.value == 0 && pg.hideReasonID.selectedIndex > 0);
pg.otherReason.style.backgroundColor = pg.otherReason.disabled ? "f5f5f5" : "ffffff";
pg.hideReasonID.focus();
}
}
I think your main problem is that you're swallowing exceptions, which is very bad. This is why "it works sometimes". Something is throwing an exception, and you're catching it, but then you're not doing anything else after that. At the very least I would display some sort of error message in your catch block.
A few other problems:
Are you sure you need those multiple try..catch blocks? The current assumption in your code is that each line that is wrapped in a try..catch is independent of the others, and execution can still proceed if something goes wrong in any one (or more) of those statements. Are you sure this is what you want? If so, there is definitely a better way of handling this.
If the statements are not independent of each other, and if a failure at any point means that execution cannot proceed, then you can wrap all of those statements in a single try..catch block and display an error message in the catch
Like I said before, swallowing exceptions is very bad! You're hiding the problem and not achieving anything. It also makes debugging extremely hard, because things will stop working and you will have no idea why (no exception, no logging, no error messages). Exceptions are used when something unexpected happens that interrupts normal program flow. It is something you definitely want to handle.
I think what you want can be done this way:
try {
if(window.opener.hideRecordReload){
window.opener.hideRecordReload(pg.recordID, pg.recordTypeID);
} else {
window.opener.pg.hideRecord(pg.recordID, pg.recordTypeID);
}
window.opener.pg.hideEncounter(pg.recordID);
window.opener.pg.hideRecordResponse(pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text);
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
window.opener.window.parent.frames[1].pg.loadQualityMeasureRequest();
window.opener.pg.closeWindow();
}
catch(e) {
console.log(e);
}
This way, if an exception occurs anywhere along those series of statements, the catch block will handle it.
Javascript also doesn't have true checked-exceptions. You can get around it by having a single try block, and inspecting the exception object that you receive*.
Expanding on what I talked about earlier, there are two ways of handling exceptions. The first way, like I showed earlier, assumes that when an exception happens, the code is in an invalid/undefined state and this therefore means that the code encountered an unrecoverable error. Another way of handling exceptions is if you know it is something you can recover from. You can do this with a flag. So:
try {
doSomething();
}
catch(e) {
error = true;
}
if(error) {
doStuffToRecoverFromError();
}
else {
doOtherStuff();
}
In this case the flow of your logic depends on an exception being thrown. The important thing is that the exception is recoverable, and depending on whether it was thrown or not, you do different things.
*Here is a somewhat contrived example that demonstrates checked-exceptions. I have two exceptions called VeryBadException and ReallyBadException that can be thrown (randomly) from two functions. The catch block handles the exception and figures out what type of exception it is by using the instanceof operator):
function VeryBadException(message) {
this.message = message;
}
function ReallyBadException(message) {
this.message = message;
}
function foo() {
var r = Math.floor(Math.random() * 4);
if(r == 2) {
throw new VeryBadException("Something very bad happened!");
}
}
function bar() {
var r = Math.floor(Math.random() * 4);
if(r == 1) {
throw new ReallyBadException("Something REALLY bad happened!");
}
}
try {
foo();
bar();
}
catch(e) {
if(e instanceof VeryBadException) {
console.log(e.message);
}
else if(e instanceof ReallyBadException) {
console.log(e.message);
}
}
It's good practice do something with the caught exceptions.
What's happening here is that if there's an error (say loading a page fails) an exception is thrown inside one of your try blocks. The corresponding catch block grabs it and says "that exception has been dealt with" but in actuality you've not done anything with it.
Try putting a print(e.Message); inside your catch blocks to find out exactly what error is causing the page not to load and then add code to your catch block to deal with this error.

How do I print debug messages in the Google Chrome JavaScript Console?

How do I print debug messages in the Google Chrome JavaScript Console?
Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print() will send the parameter to the printer.
Executing following code from the browser address bar:
javascript: console.log(2);
successfully prints message to the "JavaScript Console" in Google Chrome.
Improving on Andru's idea, you can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Just add a cool feature which a lot of developers miss:
console.log("this is %o, event is %o, host is %s", this, e, location.host);
This is the magical %o dump clickable and deep-browsable content of a JavaScript object. %s was shown just for a record.
Also this is cool too:
console.log("%s", new Error().stack);
Which gives a Java-like stack trace to the point of the new Error() invocation (including path to file and line number!).
Both %o and new Error().stack are available in Chrome and Firefox!
Also for stack traces in Firefox use:
console.trace();
As https://developer.mozilla.org/en-US/docs/Web/API/console says.
Happy hacking!
UPDATE: Some libraries are written by bad people which redefine the console object for their own purposes. To restore the original browser console after loading library, use:
delete console.log;
delete console.warn;
....
See Stack Overflow question Restoring console.log().
Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.
(Or create your own console.log() which just returns false.)
Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!
if (!window['console']) {
// Enable console
if (window['loadFirebugConsole']) {
window.loadFirebugConsole();
}
else {
// No console, use Firebug Lite
var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
if (F.getElementById(b))
return;
E = F[i+'NS']&&F.documentElement.namespaceURI;
E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
E[r]('id', b);
E[r]('src', I + g + T);
E[r](b, u);
(F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
E = new Image;
E[r]('src', I + L);
};
firebugLite(
document, 'createElement', 'setAttribute', 'getElementsByTagName',
'FirebugLite', '4', 'firebug-lite.js',
'releases/lite/latest/skin/xp/sprite.png',
'https://getfirebug.com/', '#startOpened');
}
}
else {
// Console is already available, no action needed.
}
In addition to Delan Azabani's answer, I like to share my console.js, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug:
// Create a noop console object if the browser doesn't provide one...
if (!window.console){
window.console = {};
}
// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
if (!window.console.debug && typeof window.console.log !== 'undefined') {
window.console.debug = window.console.log;
}
}
// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
for (var i = 0; i < names.length; ++i){
if(!window.console[names[i]]){
window.console[names[i]] = function() {};
}
}
Or use this function:
function log(message){
if (typeof console == "object") {
console.log(message);
}
}
Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of localConsole.debug.call() so that localConsole.debug runs in the scope of the calling class, providing access to its toString method.
localConsole = {
info: function(caller, msg, args) {
if ( window.console && window.console.info ) {
var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
if (args) {
params = params.concat(args);
}
console.info.apply(console, params);
}
},
debug: function(caller, msg, args) {
if ( window.console && window.console.debug ) {
var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
if (args) {
params = params.concat(args);
}
console.debug.apply(console, params);
}
}
};
someClass = {
toString: function(){
return 'In scope of someClass';
},
someFunc: function() {
myObj = {
dr: 'zeus',
cat: 'hat'
};
localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
}
};
someClass.someFunc();
This gives output like so in Firebug:
In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}
Or Chrome:
In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object
Personally I use this, which is similar to tarek11011's:
// Use a less-common namespace than just 'log'
function myLog(msg)
{
// Attempt to send a message to the console
try
{
console.log(msg);
}
// Fail gracefully if it does not exist
catch(e){}
}
The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.
You could use console.log() if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). Just press F12 and press the Console tab. You will see the result. Happy coding. :)
I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.
So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).
// Console extensions...
(function() {
var __localhost = (document.location.host === "localhost"),
__allow_examine = true;
if (!console) {
console = {};
}
console.__log = console.log;
console.log = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__log === "function") {
console.__log(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__info = console.info;
console.info = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__info === "function") {
console.__info(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__warn = console.warn;
console.warn = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__warn === "function") {
console.__warn(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__error = console.error;
console.error = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__error === "function") {
console.__error(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__group = console.group;
console.group = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__group === "function") {
console.__group(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert("group:\r\n" + msg + "{");
}
}
};
console.__groupEnd = console.groupEnd;
console.groupEnd = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
console.__groupEnd(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg + "\r\n}");
}
}
};
/// <summary>
/// Clever way to leave hundreds of debug output messages in the code,
/// but not see _everything_ when you only want to see _some_ of the
/// debugging messages.
/// </summary>
/// <remarks>
/// To enable __examine_() statements for sections/groups of code, type the
/// following in your browser's console:
/// top.__examine_ABC = true;
/// This will enable only the console.examine("ABC", ... ) statements
/// in the code.
/// </remarks>
console.examine = function() {
if (!__allow_examine) {
return;
}
if (arguments.length > 0) {
var obj = top["__examine_" + arguments[0]];
if (obj && obj === true) {
console.log(arguments.splice(0, 1));
}
}
};
})();
Example use:
console.log("hello");
Chrome/Firefox:
prints hello in the console window.
Internet Explorer:
displays an alert with 'hello'.
For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:
function doSomething(arg1) {
// ...
console.examine("someLabel", arg1);
// ...
}
And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):
top.__examine_someLabel = true;
Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.
Simple Internet Explorer 7 and below shim that preserves line numbering for other browsers:
/* Console shim */
(function () {
var f = function () {};
if (!window.console) {
window.console = {
log:f, info:f, warn:f, debug:f, error:f
};
}
}());
console.debug("");
Using this method prints out the text in a bright blue color in the console.
Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....
You can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log; // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Even though this question is old, and has good answers, I want to provide an update on other logging capabilities.
You can also print with groups:
console.group("Main");
console.group("Feature 1");
console.log("Enabled:", true);
console.log("Public:", true);
console.groupEnd();
console.group("Feature 2");
console.log("Enabled:", false);
console.warn("Error: Requires auth");
console.groupEnd();
Which prints:
This is supported by all major browsers according to this page:

Categories

Resources