为什么 console.log 给出行号而 console.error 没有?

Why does console.log give the line number but console.error doesn't?

如何用行号记录 JavaScript 中的错误? console.error 给出行号 index.js:1console.log 给出正确的行号。

有没有办法修改 console.error 以自动提供行号或以其他方式记录错误?

编辑: 我正在使用 ReactJS 和 react-redux。

const messageState = createSlice({
    name: 'messageState',
    initialState: {
        currentMessage: "No action has been selected"
    },
    reducers: { },
    extraReducers: {

        [recordAction]: (state, action) => {
            switch(action.payload.action) {
                case "ACTION1":
                    state.currentMessage = SELECT_ACTION1;
                    break;
                case "ACTION2":
                    state.currentMessage = SELECT_ACTION2;
                    break;
                default:
                    console.error(`messageState recordAction: Invalid action: ${action.payload.action}`);
                    return;
            }
        },

        [recordActionPosition]: (state, action) => {

            let qPos = action.payload.position.qPos;
            let rPos = action.payload.position.rPos;

            let actor = Global.entityList[action.payload.actorID];

            switch(action.payload.action) {
                case "ACTION1":
                    state.currentMessage = ACTION1_MESSAGE(actor.name, undefined, qPos, rPos);
                    break;
                case "ACTION2":
                    state.currentMessage = ACTION2_MESSAGE(actor.name, qPos, rPos);
                    break;
                default:
                    console.error(`messageState recordActionPosition: Invalid action: ${action.payload.action}`);
                    return;
            }
        }
    }
})

错误信息是messageState recordActionPosition: Invalid action: undefined ... index.js:1

尝试限制 console.error 的使用,而尝试使用 throw new Error()(但要小心,它就像一个 return 语句)

还有。请分享您的代码。当我们看不到它时,很难弄清楚它有什么问题。
您使用的是缩小文件吗?这可能是问题所在。
您使用的是 Angular、React 还是任何其他框架?可能会导致问题。
还有无数其他可能的原因。

替代解决方案:在每个错误中添加打印它来自的函数,这样您就可以找到要查看的位置以及导致错误的原因。

我怀疑您是在谈论消息在浏览器控制台中的显示方式。浏览器显示 filename/line 数字作为开发过程中的帮助,以显示错误发生的位置。添加行号的是浏览器对 console.error 的实现。使用 console.log 只是输出文本,但是 error 调用会使其更有助于识别错误发生的位置。

行号显示为 index.js:1,因为您的源代码可能已经通过预处理器,并且当浏览器 运行 将代码整合为一行时。在 运行(webpack?)之前,我们没有看到您的代码是如何打包的,所以除此之外很难给您建议。

此外,最好理解为什么要在源代码中显示行号。如果它只是在开发过程中,那么消息的文本是唯一的就足以识别它是哪一行。如果不是为了调试目的,用户为什么想知道源代码中的行号?