开发者

Validate JavaScript-Code

开发者 https://www.devze.com 2022-12-17 11:29 出处:网络
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.

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 开发者_如何学JAVAException 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?


Is there a way to validate the code before executing?

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.


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...)


closure compiler does all kinds of validating based on annotations.

https://developers.google.com/closure/compiler/docs/js-for-compiler

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号