Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

closure compiler does all kinds of validating based on annotations.

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

share|improve this answer

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.