【问题标题】:How to use a user's submitted code, and get its errors to have relevant info?如何使用用户提交的代码,并获取其错误以获取相关信息?
【发布时间】:2021-09-24 01:15:12
【问题描述】:

所以我正在为单人 浏览器 游戏 Cookie Clicker 创建一个模组。在我的模组中,我允许用户插入他们自己的代码来做他们自己的特殊事情来与我的模组的主要功能进行交互。

但是,当用户在我的自定义编辑器上编码时,我想在保存之前“测试”他们的代码,以确保不会发生错误,如果发生错误,则显示错误消息,说明他们做了什么以及在哪里做的.使用 try/catch 很容易得到错误。但我注意到错误信息是:

SynaxError: missing ) after argument list
    at new Function (<anonymous>)
    at HTMLAnchorElement.save.onclick (chrome-extension://dhdgffkkebhmkfjojejmpbldmpobfkfo/userscript.html?name=Building%2520Sorter.user.js&id=18320655-b018-42e2-8fa5-7fb0cc8d2d70:578:24)

这对我一点帮助都没有。我能从中挽救的最多的是第一行。但是,这根本不会告诉用户哪里错误位于他们的代码中。

指向假定错误的578:24 是:

try{
    //code.value is a STRING of the user's code
    let func = new Function(code.value);//<-- error points here in my source code.
    func.call(null, [[0, 1, 2], Game]);
    save.classList.remove('ModBuildingSorter_unsaved');
}
catch(e){
    console.dir(e);
}

我希望希望在用户提交时发生:

return function(array){
    return array.sort(function(building1,building2){
        return building1.price - building2.price;
    };// missing array.sort closing parenthesis
}

跑了,我可以得到syntax error,告诉我它在line 4

有什么办法可以做到这一点吗?让用户的代码有点像它自己的文件,然后尝试运行它,以便找出错误所在的行和列?

【问题讨论】:

    标签: javascript node.js error-handling


    【解决方案1】:

    理论上,您可以从 eval() 运行该函数

    即:

    try {
        let a = "function test(o){console.lo(o)}test('hello');" // Minified function
        eval(a)
    } catch (e) {
        console.log(e)
    }
    

    这是用于示例目的的未缩小函数:

    function test(o)
    {
    console.lo(o) // <-- Error
    }
    
    test('hello');
    

    这会正确返回错误,即

    TypeError: console.lo is not a function
        at test (eval at <anonymous> (D:\StackOverflowSandbox\index.js:3:5), <anonymous>:1:26)
    

    希望我有所帮助。

    【讨论】:

    • 这不可靠。例如在 eval:"function(o){console.log(o);}" 中运行时,它返回 just:Uncaught SyntaxError: Function statements require a function name 使用 eval 时出现 SyntaxErrors,不返回行位置,只是错误。我发现 ReferenceErrors 和 TypeErrors 有,但语法没有。
    猜你喜欢
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    相关资源
    最近更新 更多