JavaScript 中的“抛出新警告”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5188224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:03:52  来源:igfitidea点击:

"throw new Warning" in JavaScript?

javascripterror-handlingthrow

提问by pimvdb

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

目前我正在使用错误处理扩展我的 JavaScript 项目。该throw声明在这里发挥着重要作用:

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

这些错误使 Chrome 的开发人员工具显示一个红色叉号,但如何使其显示警告图标(黄色感叹号)?

回答by SLaks

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 consolewon't exist.

另请注意,这将在除 WebKits 或带有 Firebug 的 Firefox 之外的任何浏览器中引发错误,因为console不会存在。

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

为了解决这个问题,你可以包含Firebug Lite,或者制作一个假的 NOP-ingconsole对象。

回答by Campbeln

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.logis more widely supported than console.warn.

我在我的项目中做了类似的事情,因为console.log它比console.warn.

And if you do forget it and send it to production (which is non-muy-bueno), the anonymous function will eat it.

如果您确实忘记了它并将其发送到生产环境(非 muy-bueno),匿名函数会吃掉它。

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)

效果更好(感谢@Solomon Ucko)

回答by alex

I don't think you can throw a warning in JavaScript.

我认为您不能在 JavaScript 中发出警告。

Also, you are better off doing...

另外,你最好这样做......

throw {
   name: 'Error',
   message: 'Something error\'d'
}

According to Crockford, anyway :P

根据克罗克福德的说法,无论如何:P

回答by ThiefMaster

Use console.warn(...);

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.consoleis not defined.

请注意,它仅在有控制台时才定义 - 例如,仅当 FireBug 处于活动状态时才在 Firefox 中定义。因此,如果您使用它,请不要忘记使用 ifwindow.console未定义的方法创建一个虚拟控制台对象。

回答by Pointy

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

您可以通过确保代码拦截来自代码内部的异常,以某种方式(通过类型或鸭子类型)寻找“警告”对象来实现警告效果。

editThis 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:

编辑这多年来吸引了一些反对票,所以我将扩大答案。OP明确询问“我也可以发出警告吗?” 如果您有一个“警告”构造函数,那么答案可能是“是”:

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 usefulthings to throw are Error instances, because they come with a stack trace. In any case, there's either going to be a catchstatement or there isn't, but the browser itself won't care that your thrown object is a Warninginstance.

当你扔东西时,它们可以是任何东西,但有用的东西是 Error 实例,因为它们带有堆栈跟踪。在任何情况下,要么有一个catch声明,要么没有,但浏览器本身不会关心你抛出的对象是一个Warning实例。

As other answers have pointed out, if the realgoal 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.

正如其他答案所指出的那样,如果真正的目标只是影响控制台输出,那么它console.warn()是正确的,但当然这与扔东西没有可比性;这只是一条日志消息。继续执行,如果后续代码无法处理触发警告的情况,它仍然会失败。

回答by caffeinatedbits

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 的(正确)答案是引导我找到问题答案的原因:我可以抛出自定义的“警告”吗?目的?

Pointy pointed out that, "you can throw pretty much anything" which led me to the docs for throw:

Pointy 指出,“你几乎可以扔任何东西”,这让我找到了以下文档throw

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/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

Pointy 给出了(未确认的)正确答案,全部归功于 Pointy,我只是补充了文档和示例

P.S. Sorry Pointy, I don't even have enough reputation to upvote you (13/15) :-(

PS 抱歉 Pointy,我什至没有足够的声望来给你点赞 (13/15) :-(