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

Is it possible to prevent a specific JavaScript error from being written to the console?

本文关键字:错误 JavaScript 控制台 有可能 是否      更新时间:2023-09-26

假设—假设我有一些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之前退出,就像现在一样。我只是想防止错误显示出来。我不想使用trycatch来规避错误,或者在使用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");
    }
});