"throw new Warning" in JavaScript?
Asked Answered
H

6

70

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)?

Holds answered 4/3, 2011 at 0:9 Comment(0)
S
99

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.

Showcase answered 4/3, 2011 at 0:13 Comment(6)
On a side note, would it be possible to create a function that would replace console.warn('text');return? So basically is one able to create a function that acts as a return statement at the place the function is called?Holds
@pim: No; that's not possible. You could warn, the throw something (which isn't the same).Showcase
Warnings shouldn't affect the program flow.Ulema
If you try and warn in a browser that doesnt have console exposed it will then throw a proper error, in ie6 causing a popup. use this: function warn(a){ console&&console.warn&&console.warn(a); }Lakieshalakin
In most cases you should avoid using .warn() it is Non-standard : developer.mozilla.org/en-US/docs/Web/API/Console/warnJim
If you need the throw to stop execution, but want to log at a warning level, then you can use this pattern: try { if (somethingBad) throw new Error('Something bad happened.'); } catch (err) { console.warn(err); }Fatally
W
14

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.

Waddington answered 4/3, 2011 at 0:11 Comment(0)
S
5

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

Selfreliant answered 4/3, 2011 at 0:11 Comment(4)
You have to access the properties in the form of ex.name or ex.messageRebuild
Oh I'm sorry, it's rather useful actually.Holds
How about this? throw (Error ("o my"))Coinage
@Logan You could do that too.Selfreliant
G
5

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)

Garett answered 28/10, 2014 at 3:52 Comment(4)
if there is no console object, this code would throw an error "console is not defined". you should write (window.console ? ...Eminent
Why not use function(){} instead of function (m) { return m; })?Vaginitis
This gives me an illegal invocation warning, try/catch should work better (I'm using function(message){ try{ console.warn(message); } catch(e){ try{ console.log(message); }catch(e){} } } as a functionVaginitis
@Garett - good point. Just like "more optimal" is an oxymoron. However, there could be some sensible interpretation of "more better" - for example "7 is better then 5" and also "10 is better than 5". But 10 is "more better" ;)Apprentice
A
5

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) :-(

Airburst answered 14/3, 2019 at 21:23 Comment(0)
U
4

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.

Ulema answered 4/3, 2011 at 0:15 Comment(2)
Better yet, do window.console&&console.warn(...)Kevenkeverian
No, I don't think that's better. It ends up as a LOT of repeated code if your application is debug-heavy (ok, for warnings that's not that likely)Ulema

© 2022 - 2024 — McMap. All rights reserved.