这可以通过获取实际变量名称或详细错误消息(如浏览器控制台中打印的那个)来完成。
try {
alert(v); // v is undefined so a ReferenceError will be thrown
}
catch(err) {
alert(err.getVariableName()); // should return "v"
}
更新1:我希望从外部JS文件处理此错误,因此我尝试了以下操作:
<script>window.onerror = function(e){ console.log("caught error: "+e.message); return true;}</script>
<script src="faulty.js"></script>
但它为e.message返回undefined,尽管e.message在try-catch语句中使用时正常工作,如@ Badacadabra的回答中所述
答案 0 :(得分:1)
如果您只想要名称,可以在String.prototype.split()
上使用err.message
:
try {
alert(v);
} catch (err) {
alert(err.message.split(' ')[0]);
}
修改强>
window.onerror
处理程序具有特定签名。它的第一个参数是错误消息,其最后一个参数是Error
对象。在您的情况下,您可以这样做:
window.onerror = function (msg, url, line, col, err) {
console.log(err.message.split(' ')[0]);
}
alert(v);
或者只是这个:
window.onerror = function (msg) {
console.log(msg.split(' ')[1]);
}
alert(v);
答案 1 :(得分:0)
认为您可能必须从默认错误中使用正则表达式 来自err.message或err.stack的正则表达式
看着@ badacadra解决方案,骂我的头脑哈哈,他的解决方案很好