简体   繁体   English

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

[英]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.

相关问题 Npm 安装抛出警告旧锁文件错误 - Npm install throws warn old lockfile error 使用字符串模板将来自laravel的路由值与样式绑定时Vue警告错误 - Vue Warn Error When Binding Route Value from laravel with style using string template 将代码移动到函数中时,React-leaflet LayersControl 抛出错误 - React-leaflet LayersControl throws error when moving code into function 使用对象变量屏蔽参数时,透明代码会引发错误 - Transpiled code throws error when masking a parameter with an object variable JSON数据用作字符串,但是当对象时会引发内部错误 - JSON data works as string but throws internal error when object 如何在JavaScript代码中包含HTML标记时使JSHint发出警告? - How to make JSHint warn when HTML tags are included in JavaScript code? 页面引发TLS错误而不是加载 - Page throws TLS error instead of loading [Vue 警告]:避免使用非原始值作为键,而是使用字符串/数字值 - [Vue warn]: Avoid using non-primitive value as key, use string/number value instead 当我使用换行符渲染字符串时,ejs 会抛出“TypeError: Cannot create property '_locals' on string”错误 - When I render a string with a newline, ejs throws a “TypeError: Cannot create property '_locals' on string” error 使用对象而不是“ to”的字符串时,React-router重定向错误 - React-router Redirect error when using object instead of string for “to”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM