如何用行号在JavaScript中记录错误? console.error
给出行号index.js:1
,而console.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
答案 0 :(得分:0)
尝试限制console.error
的使用,而改为尝试throw new Error()
(但请注意,它的作用类似于return语句)
也。请分享您的代码。当我们看不到它时,很难弄清楚它是怎么了。
您使用的是缩小文件吗?可能是问题所在。
您是否正在使用Angular,React或任何其他框架?可能导致问题。
还有数以百计的其他可能原因。
替代解决方案:在打印每个错误时都会添加它的功能,以便您查找外观和原因。
答案 1 :(得分:0)
我怀疑您是在谈论该消息在浏览器控制台中的显示方式。浏览器将显示文件名/行号,以在开发过程中为您提供帮助,以显示错误发生的位置。添加行号的是浏览器的{{}}
实现。使用console.error
只是输出文本,但是调用console.log
可以使它在确定错误发生的位置上更有帮助。
行号显示为error
,因为您的源可能已通过预处理程序处理,并且当浏览器运行代码时,它已全部变为一行。我们看不到您的代码在运行之前如何打包(webpack?),因此很难为您提供建议。
另外,最好理解为什么要在源代码中显示行号。如果只是在开发过程中,则消息的文本是唯一的,足以标识其所在的行。如果不是出于调试目的,为什么用户要从源代码中知道行号?