javascript - 捕获语法错误并运行备用函数
我正在尝试在 javascript 上构建一些东西,我可以有一个可以是一切的输入 像字符串、xml、javascript 和 (不带引号的非 javascript 字符串) 如下:
//strings
eval("'hello I am a string'"); /* note the following proper quote marks */
//xml
eval(<p>Hello I am a XML doc</p>);
//javascript
eval("var hello = 2+2;");
所以前 3 个运行良好,因为它们是简单的 javascript 本机格式
,但是当我尝试在 javascript 中使用它时
//plain-text without quotes
eval("hello I am a plain text without quotes");
//--SyntaxError: missing ; before statement:--//
,显然 javascript 会解释这是语法错误,因为它认为它的 javascript 抛出了 SyntaxError。
所以我想做的是捕获这个错误并在发生这种情况时执行调整方法。
我已经尝试过 try catch 但它不起作用,因为它在尝试执行代码时不断返回语法错误。
任何帮助将不胜感激
干杯:)
附加信息:想象一个javascript将使用spidermonkey读取的外部文件,所以它是一个非浏览器的东西(我不能使用HttpRequest,DOM等。 ..)..不确定这是否重要,但确实如此。 :)
I'm trying to build something on javascript that I can have an input that can be everything
like string, xml, javascript and (non-javascript string without quotes) as follows:
//strings
eval("'hello I am a string'"); /* note the following proper quote marks */
//xml
eval(<p>Hello I am a XML doc</p>);
//javascript
eval("var hello = 2+2;");
So this first 3 are working well since they are simple javascript native formats
but when I try use this inside javascript
//plain-text without quotes
eval("hello I am a plain text without quotes");
//--SyntaxError: missing ; before statement:--//
Obviously javascript interprets this as syntax error because it thinks its javascript throwing a SyntaxError.
So what I would like to do it to catch this error and perform the adjustment method if this occurs.
I've already tried with try catch but it doesn't work since it keeps returning the Syntax error as soon as it tries to execute the code.
Any help would be much appreciated
Cheers :)
Additional Information: Imagine an external file that javascript would read, using spidermonkey, so it's a non-browser stuff(I can't use HttpRequest, DOM, etc...)..not sure if this matters, but there it is. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定 Try...Catch 块不起作用吗?这个例子在 Firefox 中适用于我。
Are you sure a Try...Catch block won't work? This example works for me in firefox.