【问题标题】:How to prevent runtime.lastError error message from appearing in console?如何防止 runtime.lastError 错误消息出现在控制台中?
【发布时间】:2019-04-09 09:31:37
【问题描述】:

我想我之前在开发 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

【问题讨论】:

  • 该错误消息具有误导性,因为它是由 C++ 开发人员编写的 :-)。您只需要在回调中访问chrome.runtime.lastError,请参阅Unchecked runtime.lastError when using Chrome API
  • @wOxxOm:谢谢。我会试试看。但这是处理异常的一种非常奇怪的方式。我只是好奇,C++ 是如何出现在这里的?
  • 您不应将try...catch 与异步 Chrome API 方法一起使用。而不是这个,在方法的回调中检查chrome.runtime.lastError
  • C++ 程序员实现了扩展 API,他们显然认为错误消息已经足够不言自明,因为它可能是为了解内部情况的人准备的。

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

这是因为异步代码。这是一个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 中运行,因为该代码已经执行完毕。

解决此问题的一种方法是使用 awaitasync 代替回调,但浏览器尚不支持它(可以在 Node 中或通过使用 Babel 来实现)

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

编辑:事实上,我的浏览器知识有点过时了。 Most modern browsers do in fact support await and async,在你的情况下,你已经使用了 chrome,所以你很好。

【讨论】:

  • 这个答案在这里不适用,因为问题不是例外(描述中使用了不正确的术语),而是 chrome 扩展 API 的内部机制,如上面链接的重复主题中所述。
  • 问题是“为什么我不能捕获异常”。上下文无关紧要。我的回答给出了一个无法捕获异常的例子。
  • 嗯,这当然是一种有趣的方法:根据上下文中的单词进行回答。
猜你喜欢
  • 2017-06-16
  • 2020-12-16
  • 1970-01-01
  • 2013-01-16
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
相关资源
最近更新 更多