是否可以防止特定的 JavaScript 错误写入控制台?

Alb*_*afe 6 javascript error-handling jquery console.log web-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");
});
Run Code Online (Sandbox Code Playgroud)

一个将在发出字符串警报时工作,并将警报后写入的消息记录到控制台。

第二第三个函数将不起作用,因为它们试图警告未定义的变量。他们的后续console.logs不会输出任何东西。

我的问题:是否可以在保持以下属性的同时防止第二个函数的错误输出到控制台?:

  • 一个功能应该按预期工作
  • 第二函数的后续console.log仍然应该执行
  • 第三函数(以及任何其他函数)仍应输出其错误

编辑:这是一个可以玩的小提琴 - https://jsfiddle.net/5m40LLmm/2/

超级编辑:我不希望第二个函数中的逻辑执行真正改变。我希望抛出错误,并且.click()处理程序应该像现在一样在到达 console.log 之前退出。我只是想防止显示错误。我不想使用tryandcatch来规避错误,或者在使用之前以某种方式检查变量是否存在alert()。我知道并希望错误发生,我只是想阻止它的显示。我希望这能让这一点更加清楚。

3oc*_*ene 2

当您运行此命令时,console.log 函数实际上从未被调用。警报函数失败,记录其失败,然后单击侦听器函数退出。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;
    }
});
Run Code Online (Sandbox Code Playgroud)