0

如何检索发生错误的行号?

在下一个脚本中,该行输出(作为最后一次raise的结果)但没有行 num。在 JSError 对象中。

from spidermonkey import Runtime, JSError

runtime = Runtime()
context = runtime.new_context()

try:
    context.execute( "function test(){ return 'OK' }; \n\ntest2()" )
except JSError as e:
    print "ERROR!"
    print "args = {0}".format( e.args )
    print "message = {0}".format( e.message )
    print "__dict__ = {0}".format( e.__dict__ )
    raise

结果:

ERROR!
args = ('ReferenceError: test2 is not defined',)
message = ReferenceError: test2 is not defined
__dict__ = {}
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    context.execute( "function test(){ return 'OK' }; \n\ntest2()" )
  File "<anonymous JavaScript>", line 3, in JavaScript code
spidermonkey.JSError: ReferenceError: test2 is not defined
4

2 回答 2

2

如果您只需要一个行号,您可以从traceback.extract_tb函数中检索它。

import sys, traceback
from spidermonkey import Runtime, JSError

runtime = Runtime()
context = runtime.new_context()

try:
    context.execute( "function test(){ return 'OK' }; \n\ntest2()" )
except JSError as e:
    info = sys.exc_info()

    print "ERROR!"
    for file, lineno, function, text in traceback.extract_tb(info[2]):
        print "line #", lineno, ": ", text
于 2013-03-30T12:34:55.333 回答
0

或许我们可以进行下一个 hack:

from spidermonkey import Runtime, JSError
import traceback # need to get text of exception
import sys

runtime = Runtime()
context = runtime.new_context()

try:
    context.execute( "function test(){ return 'OK' }; \n\ntest2()" )
except JSError as e:
    print "ERROR!"
    """print "args = {0}".format( e.args )
    print "message = {0}".format( e.message )
    print "__dict__ = {0}".format( e.__dict__ )"""

    exc_type, exc_value, exc_traceback = sys.exc_info()
    print "traceback='{0}'".format( traceback.format_exc() ) # we can parse it to get a line

如果您知道更优雅的方法,请发布它。

于 2013-03-30T12:06:50.260 回答