是否有可能防止将特定的JavaScript错误写入控制台?
Is it possible to prevent a specific JavaScript error from being written to the console?
假设—假设我有一些JavaScript来处理三个不同按钮的点击:
$("#working").click(function () {
alert("Seth Rollins is the greatest champion of all time.");
console.log("WWE World Heavyweight Champion");
});
$("#fix-this-error").click(function () {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
});
$("#should-error").click(function () {
alert(oipewavqn2389tvb3t8ahwleuhtvab3iwuthabvlewiuweaqhaoiuhva98r3b2);
console.log("This won't show either");
});
第一个将在警告字符串时工作,并将在警告之后写入的消息记录到控制台。
第二个和第三个函数将不起作用,因为它们试图警告未定义的变量。它们的后续console.logs
不会输出任何东西。
我的问题:是否有可能防止从第二个函数输出到控制台的错误,同时保持以下属性?:
- first函数应该按预期工作第二个函数的后续
console.log
仍然应该不执行第三个函数(和任何其他函数)应该仍然输出它们的错误编辑:这里有一个小提琴来玩- https://jsfiddle.net/5m40LLmm/2/
SUPER EDIT:我不想让second函数中的逻辑执行发生真正的变化。我希望抛出错误,并且.click()
处理程序应该在到达console.log之前退出,就像现在一样。我只是想防止错误显示出来。我不想使用try
和catch
来规避错误,或者在使用alert()
之前以某种方式检查变量是否存在。我知道并且想要错误发生,我只是想阻止它的显示。
使用try catch
$("#fix-this-error").click(function () {
try {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
} catch() {}
});
运行此命令时,实际上永远不会调用console.log函数。alert函数失败,记录失败,并退出click listener函数。从未到达console.log()
。这意味着您只需要阻止警报显示错误。这就是try catch语句有用的地方。
$("#fix-this-error").click(function () {
try {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
} catch (e) {
// Code jumps here when `alert()` fails.
// `e` stores information about the error
// If you don't want to put everything in the try/catch,
// you can stop the function from continuing execution with
return;
}
});
使用typeof
关键字检查是否定义了特定变量
typeof文档
$("#fix-this-error").click(function () {
if (typeof this_should_not_show_up_in_the_console !== "undefined")
{
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
}
});
相关文章:
- object响应时出现对象错误javascript
- 未捕获的语法错误:javascript对象上出现意外的标记ILLEGAL
- Phonegap-Android 4.4-html5音频长度错误(javascript和媒体插件)
- 未捕获的语法错误:javascript中出现意外的标记}
- 如何从 MVC4 链接调用 Javascript 方法(错误 JavaScript 运行时错误:对象不支持此操作)
- 未捕获类型错误javascript方法
- 将字符串返回到类型为“0”的输出字段;数字“;针对用户错误javascript
- 解析器错误(Javascript初学者寻找解决方案)
- IE 错误 .JavaScript 运行时错误:对象不支持属性或方法“preventDefault”
- appendChild 不是函数错误 (JAVASCRIPT)
- 错误 JavaScript 函数
- 而循环抛出错误JavaScript
- 意外的类型错误 - Javascript,多维数组
- 语法错误:Javascript 中的意外令牌/将数据发布到 Amazon s3
- 语法错误:Javascript 中缺少指数
- 错误“JavaScript 运行时错误:查找滚动位置时无法获取未定义或空引用的属性'scrollLeft'”
- 错误 JavaScript 循环数组
- 错误:Javascript 上的 [对象对象]
- IndexedDBShim.js错误:JavaScript运行时错误:在严格模式下不允许分配只读属性
- 在Evernote listNotebooks API上获取错误-Javascript/Node.Js