"throw new Warning" in JavaScript?

pimvdb picture pimvdb · Mar 4, 2011 · Viewed 31k times · Source

At the moment I'm extending my JavaScript project with error handling. The throw statement is playing an important role here:

throw new Error("text"); // Error: text

However, can I also throw a warning? I tried the following to no avail:

throw new Warning("text"); // Warning is not defined

The errors make Chrome's Developer Tools show a red cross, but how can I make it display a warning icon (yellow exclamation mark)?

Answer

SLaks picture SLaks · Mar 4, 2011

Like this:

console.warn('Hi!');

Note that unlike exceptions, this will not interrupt your code; the calling function will continue normally.

Also note that this will throw an error in any browser except for WebKits or Firefox with Firebug, because console won't exist.

To fix that, you can include Firebug Lite, or make a fake NOP-ing console object.