简体   繁体   English

Chrome 扩展中的异常处理

[英]Exception handling in Chrome extensions

I can't seem to find anything in the Chrome extension documentation about exception handling.我似乎无法在 Chrome 扩展文档中找到有关异常处理的任何内容。 All the asynchronous apis makes it very difficult without littering the code with try / catch statements everywhere..所有的异步 api 都很难避免在代码中到处乱放 try/catch 语句。

How can I add a global exception handler to my background page that'll allow me to do some resource cleanup in the case of an exception?如何将全局异常处理程序添加到我的后台页面,以便在发生异常时进行一些资源清理?

You can get the error in the execute script callback with chrome.runtime.lastError :您可以使用chrome.runtime.lastError在执行脚本回调中获取错误:

chrome.tabs.executeScript(tabId, details, function() {
    if (chrome.runtime.lastError) {
       var errorMsg = chrome.runtime.lastError.message
       if (errorMsg == "Cannot access a chrome:// URL") {
           // Error handling here
       }
    }
})

I haven't been able to find a global error handler but I was able to come up with a solution that works just as well.我一直无法找到全局错误处理程序,但我能够提出一个同样有效的解决方案。

It does depend on what methods you're calling though.不过,这确实取决于您调用的方法。 Most of my errors came from calling chrome.tabs.executeScript() on a chrome:// page or a chrome webstore page.我的大部分错误来自在chrome://页面或 chrome 网上商店页面上调用chrome.tabs.executeScript() The last parameter of this function is a callback that contains a results array.此函数的最后一个参数是包含results数组的回调。 I found that if this was undefined I was getting an error back.我发现如果这是undefined我会收到一个错误。 This way I was able to set up a simple error handling function to notify the user when there was an error.通过这种方式,我能够设置一个简单的错误处理功能,以在出现错误时通知用户。

chrome.tabs.executeScript(null, {file: '/path/to/file.js'}, function(results) {
    if (results === undefined) {
        // Fire error handling code
    }
});

Again, Idk if this is applicable with the methods that you're calling but I was able to do what I wanted this way.再次,如果这适用于您正在调用的方法,但我能够以这种方式做我想做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM