[英]Warn when code throws a string instead of an error
Sometimes in JavaScript, people will write throw 'Something went wrong';
有时在JavaScript中,人们会写出
throw 'Something went wrong';
instead of throw Error('something went wrong');
而不是
throw Error('something went wrong');
The first example is totally valid JS, but is not ideal because strings don't have stack traces, but errors do. 第一个例子是完全有效的JS,但并不理想,因为字符串没有堆栈跟踪,但错误确实如此。 Can the Closure Compiler warn when code is throwing strings instead of throwing errors?
Closure Compiler可以在代码抛出字符串而不是抛出错误时发出警告吗?
You can do this using a JS Conformance file. 您可以使用JS Conformance文件执行此操作。 Full details are here , but essentially you create a file
js_conformance.txt
: 完整的详细信息在这里 ,但基本上你创建一个文件
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 }'
}
and pass it to the compiler using --conformance_configs=js_conformance.txt
并使用
--conformance_configs=js_conformance.txt
将其传递给编译器
If there are a lot of existing throw 'string'
s in your codebase, you can clean them up using RefasterJS . 如果你的代码库中有很多现有的
throw 'string'
,你可以使用RefasterJS清理它们。
This video is a nice intro to both the conformance checks and RefasterJS. 这个视频是一致性检查和RefasterJS的一个很好的介绍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.