javascript - 如何防止 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
解决方案
这是由于异步代码而发生的。这是一个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 中运行,因为该代码已经完成执行。
解决这个问题的一种方法是使用await
andasync
而不是回调,但浏览器还不支持它(可以在 Node 中或通过使用 Babel 来实现)
正如@wOxxOm 建议的那样,对于您的特定问题,请查看Unchecked runtime.lastError when using Chrome API
编辑:事实上,我的浏览器知识有点过时了。大多数现代浏览器实际上都支持await
andasync
,而且在你的情况下,你已经使用了 chrome,所以你很好。
推荐阅读
- mysql - 选择操作期间列名不明确错误
- raku - Python中是否有类似于Counter的内置方法?
- r - 如何在R中找到二项式随机变量的平均值?
- php - 将数组转换为 Json 以保存到数据库
- amazon-web-services - Terraform 找不到匹配的安全组
- sql - postgres - 查询 jsonb 数组字段中的唯一值
- python - Flask 开发环境在导入views.py 时中断
- android - 在 updateAppWidget 内更新的小部件不显示任何列表数据
- marklogic - Marklogic 如何将 xquery 转换为 cts javascript
- json - 从 Firefox 中的本地 html 文件调用 Jenkins Jason REST API 而无需更改服务器