Javascript:错误位置评估JS函数(';…我的代码为字符串';)

Javascript:错误位置评估JS函数(';…我的代码为字符串';),javascript,stacktrace.js,Javascript,Stacktrace.js,我们有一些定义javascript函数的用户定义字段,希望在抛出错误时向用户显示位置(行、列)。例如: userFunc = new Function('context', '{ let a = 0; \n context.missingFunction(); return 2; }'); 在计算userFunc时 userFunc({}); 将引发一个异常,如下所示: context.missingMeethod is not a function 是否有一个库可以在所有现代浏览

我们有一些定义javascript函数的用户定义字段,希望在抛出错误时向用户显示位置(行、列)。例如:

userFunc = new Function('context',  '{  let a = 0; \n context.missingFunction(); return 2; }');
在计算userFunc时

userFunc({});
将引发一个异常,如下所示:

 context.missingMeethod is not a function 
是否有一个库可以在所有现代浏览器中检索错误的位置(例如:第2行第12列)

堆栈分析器库(来自StacktraceJS)未检索信息时出错。在Chrome中,stacktrace看起来像(位置是匿名的):

TypeError:context.missingMeethod不是函数
在评估时(评估时)(http://localhost:3000/icCube/reporting/static/js/main.chunk.js:28541:66), :2:12)

这至少在Chrome、Firefox和Safari中是可能的。我不确定这是否能很好地概括,但它可能会给你一些工作的依据

镀铬:

getErrorPosition = (userFunc) => {
    try {
        userFunc({});
        return null;
    } catch (error) {
        const relevantLine = error.stack.split('\n')[1];
        const regex = /<anonymous>:(\d+):(\d+)\)/g;
        const match = regex.exec(relevantLine);
        if (match) {
            return {
                line: parseInt(match[1], 10),
                column: parseInt(match[2], 10)
            };
        } else {
            return null;
        }
    }
}
在Firefox中:

getErrorPosition = (userFunc) => {
    try {
        userFunc({});
        return null;
    } catch (error) {
        const relevantLine = error.stack.split('\n')[0];
        const regex = /Function:(\d+):(\d+)/g;
        const match = regex.exec(relevantLine);
        if (match) {
            return {
                line: parseInt(match[1], 10),
                column: parseInt(match[2], 10)
            };
        } else {
            return null;
        }
    }
}

在错误堆栈解析器()中存在此问题。如果你热衷于贡献,你可以帮助成千上万使用图书馆的人。请编写一个单元测试:)
getErrorPosition = (userFunc) => {
    try {
        userFunc({});
        return null;
    } catch (error) {
        return {
            line: error.line,
            column: error.column,
        };
    }
}
getErrorPosition = (userFunc) => {
    try {
        userFunc({});
        return null;
    } catch (error) {
        const relevantLine = error.stack.split('\n')[0];
        const regex = /Function:(\d+):(\d+)/g;
        const match = regex.exec(relevantLine);
        if (match) {
            return {
                line: parseInt(match[1], 10),
                column: parseInt(match[2], 10)
            };
        } else {
            return null;
        }
    }
}