javascript - 捕获SyntaxError并运行备用函数 [英] javascript - catch SyntaxError and run alternate function
问题描述
我正在尝试在javascript上构建一些东西,我可以输入一些
,如string,xml,javascript和(非javascript字符串,不带引号)如下:
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;");
因此,前3个版本运行良好,因为它们是简单的javascript原生格式
So this first 3 are working well since they are simple javascript native formats
但是当我尝试在javascript中使用它时
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:--//
显然javascript将此解释为语法错误,因为它认为它的javascript抛出了SyntaxError。
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.
我已经尝试过try catch但是它不起作用,因为它一旦尝试执行代码就会一直返回语法错误。
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.
任何非常感谢帮助
干杯:)
其他信息:想象一下javascript会读取的外部文件,使用spidermonkey,所以它是非浏览器的东西(我不能使用HttpRequest,DOM等...)..不确定这是否重要,但确实如此。 :)
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. :)
推荐答案
你确定试试...... Catch 块无效?这个例子适用于firefox。
Are you sure a Try...Catch block won't work? This example works for me in firefox.
try {
eval("hello I am a plain text without quotes");
} catch(err) {
alert("error caught");
}
这篇关于javascript - 捕获SyntaxError并运行备用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!