how can I compile javascript code in golang and get the detail error

huangapple go评论78阅读模式
英文:

how can I compile javascript code in golang and get the detail error

问题

我正在使用Go语言进行一个项目。我需要在Go中运行一段JavaScript代码。我知道有一个叫做otto的包可以实现这个功能。我的问题是如何获取JavaScript代码的详细错误信息。例如:

src :=`
      abc = 2 + 
      console.log("The value of abc is " + abc)
 `

当我执行compile(src)时,我会得到以下错误信息:
第二行缺少某些内容,第三行缺少分号,就像编译器一样。

在发布问题之前,我已经尝试使用otto的编译函数,但返回的错误为nil。
对于上述代码,使用func (self Otto) Run(src interface{}) (Value, error)会返回错误,但如果代码变成:

abc = 9
abc = 2 + 
console.log("The value of abc is " + abc) 

对于func (self Otto) Run(src interface{}) (Value, error)func (self *Otto) Compile(filename string, src interface{}) (*Script, error),错误都是nil。

英文:

I am using go language for a project. I need run a piece of js code in go. I know there is an package which is otto. My problem is that how I get the detail error message for the js code. For example:

src :=`
      abc = 2 + 
      console.log("The value of abc is " + abc)
 `

and when I do something let's say compile(src).
Then I will get the error that:
Miss something at second line and miss ';' at third line.
just like a compiler doing

I already try using the compile of otto before I post the problem, the returned error is nil.
Using func (self Otto) Run(src interface{}) (Value, error) of otto for above code will return error, but if the code became

abc = 9
abc = 2 + 
console.log("The value of abc is " + abc) 

for both func (self Otto) Run(src interface{}) (Value, error) and func (self *Otto) Compile(filename string, src interface{}) (*Script, error) the error are nil

答案1

得分: 1

我会为你进行不足的研究进行扣分。简单地在Google上搜索"golang otto"会出现GitHub页面。有一个相当不错的README.markdown文件用于文档说明。请阅读它。

然后你会发现Otto有以下内容:

func (self *Otto) Compile(filename string, src interface{}) (*Script, error)

这是最好的方法了。运行它,看看返回的错误值是什么。

此外,根据文档:

type Error struct {
}

Error代表运行时错误,例如TypeError、ReferenceError等。

func (err Error) Error() string

Error返回错误的描述。

func (err Error) String() string

String返回错误的描述以及错误发生的跟踪。
英文:

I'm going to ding you for insufficient research. A simple Google of "golang otto" brought up the Github page. With a pretty decent README.markdown for documentation. Read it.

Then you find out that Otto has

func (self *Otto) Compile(filename string, src interface{}) (*Script, error)

That is as good as it gets. Run that, see what you get in the returned error value.

Also from the documentation:

type Error struct {
}

An Error represents a runtime error, e.g. a TypeError, a ReferenceError, etc.

func (err Error) Error() string

Error returns a description of the error

func (err Error) String() string

String returns a description of the error and a trace of where the error occurred.

huangapple
  • 本文由 发表于 2017年9月5日 11:06:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/46046434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定