验证 JavaScript 代码
我使用Java的ScriptEngine来执行JavaScript代码。我使用可调用接口,这样我就可以将脚本代码用作实现 Java 接口的普通 Java 对象。
如果 JavaScript 代码
- 无效
- 且不遵循接口(缺少方法、错误的返回类型、引发异常等),
我会在执行代码时收到来自 Rhino 的内部异常或 UndeclaredThrowableException。两者都是 RuntimeException,“不允许”捕获它们。
有没有办法在执行之前验证代码?或者我必须打破这里的规则并捕获 RuntimeExceptions 吗?这对我有用,但最优雅的方式是什么?
I use Java's ScriptEngine to execute JavaScript Code. I use the Invocable Interface, so that I can use the Script Code as a normal Java Object implementing a Java Interface.
If the JavaScript Code
- is invalid
- does not follow the interface (missing methods, wrong return type, throws an exception etc.)
I get an internal Exception from Rhino or an UndeclaredThrowableException while executing the code. Both are RuntimeExceptions, which are not "allowed" to catch.
Is there a way to validate the code before executing? Or do I have to break the rule here and catch RuntimeExceptions? That would work for me, but what is the most elegant way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不会。JavaScript 是松散类型的,没有接口的概念,并且是动态解释的。
如果不设计自己的验证框架,您能做的最好的事情就是使用 JSLint 检查语法错误。
No. JavaScript is loosely typed, has no concept of interfaces and is interpreted on the fly.
Without designing your own validation framework, the best you can do is check it for syntax errors with JSLint.
几年后......对于其他偶然发现这一点的人:
您可以使用严格模式,通过使用
"use strict";
http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
一些代码编辑器提供实时验证(语法...)
A few years later... for others who stumble on this:
You can use strict mode which adds more runtime checks by using
"use strict";
http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
Some code editors provide realtime validation (syntax...)
闭包编译器根据注释进行各种验证。
https://developers.google.com/closure/compiler/docs/js -用于编译器
closure compiler does all kinds of validating based on annotations.
https://developers.google.com/closure/compiler/docs/js-for-compiler