首页 > 解决方案 > 如何防止 runtime.lastError 错误消息出现在控制台中?

问题描述

我想我之前在开发 Chrome 扩展程序时处理过这个问题,所以现在在日常维护期间,同样的问题似乎又出现了。

有人可以让我知道为什么这段代码:

    try
    {
        chrome.tabs.get(nTabID, function(tab)   //this is line 484 where the error happens
        {
            var tabUrl = '';

            try
            {
                tabUrl = tab.url;
            }
            catch(e)
            {
                //Failed to get tab URL -- mute it
            }

            if(tabUrl)
            {
                //Process it
            }
        });
    }
    catch(e)
    {
        //Failed to get tab for 'nTabID' -- mute it
    }

无法在控制台中阻止此错误:

在此处输入图像描述

运行 tabs.get 时未选中 runtime.lastError:没有 ID 的选项卡:N

标签: javascriptgoogle-chromegoogle-chrome-extension

解决方案


这是由于异步代码而发生的。这是一个repl,可以帮助您理解。下面是独立的代码,大家可以玩弄一下就明白了。取消注释下面的每个错误都会以不同的方式触发异常。

// Mock of chrome.tabs.get, for illustration purposes
function chromeTabsGet(tabId, callback) {
    // v----------------- This error will be caught
    // throw Error();
    setTimeout(() => {
        // v------------- This error will not (just like the one you see)
        throw Error()
        callback({url: 2})
    }, 0)
}


try
{
    chromeTabsGet(0, function(tab)   //this is line 484 where exception happens
    {
        var tabUrl = '';

        try
        {
            tabUrl = tab.url;
        }
        catch(e)
        {
            // Failed to get tab URL -- mute it
        }

        if(tabUrl)
        {
            // Process it
        }
    });
}
catch(e)
{
    // Failed to get tab for 'nTabID' -- mute it
}

如您所见,chrome.tabs.get(如图所示chromeTabsGet)可以通过两种方式进行投掷。如果它抛出函数本身,那么您将立即在最外层的 try-catch 中捕获它。但是,如果函数调度一个(或多个)异步事件,那么这些事件就会脱离主控制流,被放入事件循环队列中,稍后再调度。由于这个原因,它们不再在您的 try-catch 中运行,因为该代码已经完成执行。

解决这个问题的一种方法是使用awaitandasync而不是回调,但浏览器还不支持它(可以在 Node 中或通过使用 Babel 来实现)

正如@wOxxOm 建议的那样,对于您的特定问题,请查看Unchecked runtime.lastError when using Chrome API

编辑:事实上,我的浏览器知识有点过时了。大多数现代浏览器实际上都支持awaitandasync,而且在你的情况下,你已经使用了 chrome,所以你很好。


推荐阅读