最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Validate JavaScript-Code - Stack Overflow

programmeradmin4浏览0评论

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?

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 asked Jan 14, 2010 at 11:20 ThomasThomas 532 silver badges4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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/blog/ecmascript-5-strict-mode-json-and-more/

Some code editors provide realtime validation (syntax...)

closure piler does all kinds of validating based on annotations.

https://developers.google./closure/piler/docs/js-for-piler

发布评论

评论列表(0)

  1. 暂无评论