简体   繁体   中英

Exception handling in Chrome extensions

I can't seem to find anything in the Chrome extension documentation about exception handling. All the asynchronous apis makes it very difficult without littering the code with try / catch statements everywhere..

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.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. The last parameter of this function is a callback that contains a results array. I found that if this was undefined I was getting an error back. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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