代码抛出字符串而不是错误时发出警告

时间:2014-12-10 21:14:58

标签: javascript google-closure-compiler

有时在JavaScript中,人们会写throw 'Something went wrong';而不是throw Error('something went wrong');

第一个例子是完全有效的JS,但并不理想,因为字符串不具有堆栈跟踪,但错误确实如此。 Closure Compiler可以在代码抛出字符串而不是抛出错误时发出警告吗?

1 个答案:

答案 0 :(得分:3)

您可以使用JS Conformance文件执行此操作。完整详细信息为here,但基本上您创建了一个文件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进行清理。

This video is a nice intro to both the conformance checks and RefasterJS.

相关问题