簡體   English   中英

代碼拋出字符串而不是錯誤時發出警告

[英]Warn when code throws a string instead of an error

有時在JavaScript中,人們會寫出throw 'Something went wrong'; 而不是throw Error('something went wrong');

第一個例子是完全有效的JS,但並不理想,因為字符串沒有堆棧跟蹤,但錯誤確實如此。 Closure Compiler可以在代碼拋出字符串而不是拋出錯誤時發出警告嗎?

您可以使用JS Conformance文件執行此操作。 完整的詳細信息在這里 ,但基本上你創建一個文件js_conformance.txt

requirement: {
  type: BANNED_CODE_PATTERN
  error_message: 'The use of throw with a string is not allowed. Throw an Error object instead.'

  value: '/** @param {string|String} str */ function template(str) { throw str }'
}

並使用--conformance_configs=js_conformance.txt將其傳遞給編譯器

如果你的代碼庫中有很多現有的throw 'string' ,你可以使用RefasterJS清理它們。

這個視頻是一致性檢查和RefasterJS的一個很好的介紹。

暫無
暫無

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

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