gpt4 book ai didi

javascript - 如何防止控制台中出现runtime.lastError错误消息?

转载 作者:行者123 更新时间:2023-11-28 11:00:37 25 4
gpt4 key购买 nike

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

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

enter image description here

Unchecked runtime.lastError while running tabs.get: No tab with ID: N

最佳答案

这是由于异步代码而发生的。这是一个可以帮助您理解的回复。下面是独立的代码,你可以自己玩一下来理解。取消注释下面的每个错误都会以不同的方式触发异常。

// 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,所以你很好。

关于javascript - 如何防止控制台中出现runtime.lastError错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55589519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com