Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
Kimble Avatar asked Jan 25 '13 07:01

Kimble


2 Answers

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
       }
    }
})
like image 197
lluft Avatar answered Oct 04 '22 00:10

lluft


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.

like image 32
Chris Dolphin Avatar answered Oct 04 '22 02:10

Chris Dolphin