"throw new Warning" in JavaScript?
JavascriptError HandlingThrowJavascript Problem Overview
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)?
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
There's no such thing as a "warning" exception. When you throw an object (and you can throw pretty much anything), it's an exception that's either caught or not.
You could possibly achieve a warning effect by making sure your code intercepts exceptions coming up from inside your code, looking for "warning" objects somehow (by type or by duck-typing).
edit This has attracted some downvotes over the years, so I'll expand on the answer. The OP asked explicitly "can I also throw a warning?" The answer to that could be "yes" if you had a "Warning" constructor:
function Warning(msg) {
this.msg = msg;
}
Then you could certainly do
if (somethingIsWrong())
throw new Warning("Something is wrong!");
Of course, that'll work, but it's not a whole lot different from
if (somethingIsWrong())
throw "Something is wrong!";
When you're throwing things, they can be anything, but the useful things to throw are Error instances, because they come with a stack trace. In any case, there's either going to be a catch
statement or there isn't, but the browser itself won't care that your thrown object is a Warning
instance.
As other answers have pointed out, if the real goal is just affecting console output, then console.warn()
is correct, but of course that's not really comparable to throwing something; it's just a log message. Execution continues, and if subsequent code can't deal with the situation that triggered the warning, it'll still fail.
Solution 3 - Javascript
I don't think you can throw a warning in JavaScript.
Also, you are better off doing...
throw {
name: 'Error',
message: 'Something error\'d'
}
According to Crockford, anyway :P
Solution 4 - Javascript
In order to be safe, you can do this:
(console ? (console.warn || console.log) : function (m) { return m; })
("warning text goes here")
;
I do something similar in my projects since console.log
is more widely supported than console.warn
.
And if you do forget it and send it to production (which is non-muy-bueno), the anonymous function will eat it.
EDIT:
var notConsole = {
log: function() {
try {
console.log.apply(this, arguments);
} catch(e) {}
},
warn: function() {
try {
console.warn.apply(this, arguments);
} catch(e) {}
}
}
Works much more better (thanks @Solomon Ucko)
Solution 5 - Javascript
Use console.warn(...);
Note that it is only defined if there's a console - e.g. in Firefox only if FireBug is active. So if you use that, don't forget to create a dummy console object with the method you use if window.console
is not defined.
Solution 6 - Javascript
Just in case anyone is still searching for this years later as I just was now, I'd like to point out that Pointy's (correct) answer is what lead me to finding the answer to my question: can I throw a custom "Warning" object?
Pointy pointed out that, "you can throw pretty much anything" which led me to the docs for throw
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
Excerpts:
// Syntax
throw expression; // expression to throw
// Examples
throw 'Error2'; // generates an exception with a string value
throw 42; // generates an exception with the value 42
throw true; // generates an exception with the value true
throw new Error('Required'); // generates an error object with the message of Required
// Throw an object - you can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.
// Example
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
function getMonthName(mo) {
mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (months[mo] !== undefined) {
return months[mo];
} else {
throw new UserException('InvalidMonthNo');
}
}
try {
// statements to try
var myMonth = 15; // 15 is out of bound to raise the exception
var monthName = getMonthName(myMonth);
} catch (e) {
monthName = 'unknown';
console.log(e.message, e.name); // pass exception object to err handler
}
Full credit still goes to Pointy for giving the (unacknowledged) correct answer, I'm just supplementing with docs and examples
P.S. Sorry Pointy, I don't even have enough reputation to upvote you (13/15) :-(