簡體   English   中英

在JavaScript中“拋出新警告”?

[英]“throw new Warning” in JavaScript?

目前我正在通過錯誤處理擴展我的JavaScript項目。 throw語句在這里發揮着重要作用:

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

但是,我還可以發出警告嗎? 我嘗試了以下無濟於事:

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

錯誤使Chrome的開發人員工具顯示紅叉,但如何讓它顯示警告圖標(黃色感嘆號)?

像這樣:

console.warn('Hi!');

請注意,與異常不同,這不會中斷您的代碼; 調用函數將繼續正常。

另請注意,除了帶有Firebug的WebKits或Firefox之外,這將在任何瀏覽器中引發錯誤,因為console將不存在。

要解決這個問題,您可以包含Firebug Lite ,或制作虛假的NOP-ing console對象。

為了安全起見,您可以這樣做:

(console ? (console.warn || console.log) : function (m) { return m; })
    ("warning text goes here")
;

我在我的項目中做了類似的事情,因為console.logconsole.warn支持得更廣泛。

如果你忘記它並將其發送到生產( 非muy-bueno ),匿名函數將吃掉它。

編輯:

var notConsole = {
    log: function() {
        try {
            console.log.apply(this, arguments);
        } catch(e) {}
    },
    warn: function() {
        try {
            console.warn.apply(this, arguments);
        } catch(e) {}
    }
}

工作得更好(感謝@Solomon Ucko)

使用console.warn(...);

請注意,只有在有控制台的情況下才會定義它 - 例如,只有在FireBug處於活動狀態時才在Firefox中定義。 因此,如果您使用它,請不要忘記使用您未使用window.console定義的方法創建虛擬控制台對象。

沒有“警告”例外。 當你拋出一個物體(並且你可以扔幾乎任何東西 )時,這是一個例外,無論是否被捕獲。

您可以通過確保代碼攔截代碼中出現的異常,以某種方式查找“警告”對象(按類型或通過鴨子類型)來實現警告效果。

編輯多年來,這引起了一些人的反對,所以我將擴大答案。 OP明確詢問“我是否也可以發出警告?” 如果你有一個“警告”構造函數,答案可能是“是”:

function Warning(msg) {
  this.msg = msg;
}

那你當然可以

if (somethingIsWrong())
  throw new Warning("Something is wrong!");

當然,這會起作用,但它與眾不同

if (somethingIsWrong())
  throw "Something is wrong!";

當你扔東西時,它們可以是任何東西,但拋出的有用東西是錯誤實例,因為它們帶有堆棧跟蹤。 在任何情況下,要么是一個catch語句,要么沒有,但瀏覽器本身並不關心你的拋出對象是一個Warning實例。

正如其他答案所指出的那樣,如果真正的目標只是影響控制台輸出,那么console.warn()是正確的,但當然這與扔東西不太相似; 它只是一條日志消息。 執行繼續,如果后續代碼無法處理觸發警告的情況,它仍然會失敗。

我不認為你可以在JavaScript中發出警告。

另外,你最好做...

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

根據克羅克福德的說法,無論如何:P

為了防止今后有人像我現在一樣仍在尋找這些年,我想指出Pointy的(正確的)答案是讓我找到我的問題的答案:我可以拋出一個自定義的“警告”賓語?

Pointy指出,“你可以扔幾乎任何東西”,這導致我throw文件:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

摘錄:

// 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
}

對於提供(未經確認的)正確答案的Pointy仍有充分的信用,我只是補充了文檔和示例

PS對不起尖銳,我甚至沒有足夠的聲譽來支持你(13/15):-(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM