refactor: selective catches in Chrome extension files

Convert empty catches and error-swallowing patterns across inspector.js,
content.js, background.js, and sidepanel.js. DOM catches filter
TypeError/DOMException, chrome API catches filter Extension context
invalidated, network catches filter Failed to fetch. Unexpected errors
now propagate.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Garry Tan 2026-04-09 04:54:32 -10:00
parent b8c4e703c6
commit 5f9246ac23
No known key found for this signature in database
GPG Key ID: C1F69E85C74EFE1D
4 changed files with 37 additions and 22 deletions

View File

@ -46,7 +46,8 @@ async function loadAuthToken() {
if (data.token) authToken = data.token; if (data.token) authToken = data.token;
} }
} catch (err) { } catch (err) {
console.error('[gstack bg] Failed to load auth token:', err.message); if (!err?.message?.includes('Failed to fetch')) throw err;
console.debug('[gstack bg] Auth token not available (server may not be running):', err.message);
} }
} }
@ -125,7 +126,8 @@ async function notifyContentScripts(type) {
} }
} }
} catch (err) { } catch (err) {
console.error('[gstack bg] Failed to query tabs for notification:', err.message); if (!err?.message?.includes('Extension context invalidated')) throw err;
console.debug('[gstack bg] Tab notification skipped (extension context invalidated)');
} }
} }
@ -180,7 +182,8 @@ async function fetchAndRelayRefs() {
} }
} }
} catch (err) { } catch (err) {
console.error('[gstack bg] Failed to fetch/relay refs:', err.message); if (!err?.message?.includes('Failed to fetch')) throw err;
console.debug('[gstack bg] Refs fetch skipped (server unreachable)');
} }
} }
@ -203,13 +206,15 @@ async function injectInspector(tabId) {
files: ['inspector.css'], files: ['inspector.css'],
}); });
} catch (err) { } catch (err) {
if (!err?.message?.includes('Extension context invalidated') && !err?.message?.includes('Cannot access')) throw err;
console.debug('[gstack bg] Inspector CSS injection failed (non-fatal):', err.message); console.debug('[gstack bg] Inspector CSS injection failed (non-fatal):', err.message);
} }
// Send startPicker to the injected inspector.js // Send startPicker to the injected inspector.js
try { try {
await chrome.tabs.sendMessage(tabId, { type: 'startPicker' }); await chrome.tabs.sendMessage(tabId, { type: 'startPicker' });
} catch (err) { } catch (err) {
console.warn('[gstack bg] Failed to send startPicker:', err.message); if (!err?.message?.includes('Extension context invalidated') && !err?.message?.includes('Receiving end does not exist')) throw err;
console.debug('[gstack bg] startPicker skipped (tab not ready):', err.message);
} }
inspectorMode = 'full'; inspectorMode = 'full';
return { ok: true, mode: 'full' }; return { ok: true, mode: 'full' };
@ -232,7 +237,8 @@ async function stopInspector(tabId) {
try { try {
await chrome.tabs.sendMessage(tabId, { type: 'stopPicker' }); await chrome.tabs.sendMessage(tabId, { type: 'stopPicker' });
} catch (err) { } catch (err) {
console.debug('[gstack bg] Failed to stop picker on tab', tabId, ':', err.message); if (!err?.message?.includes('Extension context invalidated') && !err?.message?.includes('Receiving end does not exist')) throw err;
console.debug('[gstack bg] stopPicker skipped (tab not ready):', err.message);
} }
return { ok: true }; return { ok: true };
} }
@ -270,7 +276,8 @@ async function sendToContentScript(tabId, message) {
try { try {
const response = await chrome.tabs.sendMessage(tabId, message); const response = await chrome.tabs.sendMessage(tabId, message);
return response || { ok: true }; return response || { ok: true };
} catch { } catch (e) {
if (!e?.message?.includes('Extension context invalidated') && !e?.message?.includes('Receiving end does not exist')) throw e;
return { error: 'Content script not available' }; return { error: 'Content script not available' };
} }
} }

View File

@ -207,11 +207,11 @@ function captureBasicData(el) {
source: sheet.href || 'inline', source: sheet.href || 'inline',
}); });
} }
} catch { /* skip rules that can't be matched */ } } catch (e) { if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e; }
} }
} catch { /* cross-origin sheet — silently skip */ } } catch (e) { if (!(e instanceof DOMException)) throw e; }
} }
} catch { /* CSSOM not available */ } } catch (e) { if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e; }
return { computedStyles, boxModel, matchedRules }; return { computedStyles, boxModel, matchedRules };
} }
@ -219,7 +219,7 @@ function captureBasicData(el) {
function basicBuildSelector(el) { function basicBuildSelector(el) {
if (el.id) { if (el.id) {
const sel = '#' + CSS.escape(el.id); const sel = '#' + CSS.escape(el.id);
try { if (document.querySelectorAll(sel).length === 1) return sel; } catch {} try { if (document.querySelectorAll(sel).length === 1) return sel; } catch (e) { if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e; }
} }
const parts = []; const parts = [];
let current = el; let current = el;

View File

@ -159,7 +159,8 @@
function isUnique(selector) { function isUnique(selector) {
try { try {
return document.querySelectorAll(selector).length === 1; return document.querySelectorAll(selector).length === 1;
} catch { } catch (e) {
if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e;
return false; return false;
} }
} }
@ -244,11 +245,11 @@
source: sheet.href || 'inline', source: sheet.href || 'inline',
}); });
} }
} catch { /* skip rules that can't be matched */ } } catch (e) { if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e; }
} }
} catch { /* cross-origin sheet — silently skip */ } } catch (e) { if (!(e instanceof DOMException)) throw e; }
} }
} catch { /* CSSOM not available */ } } catch (e) { if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e; }
return { computedStyles, boxModel, matchedRules }; return { computedStyles, boxModel, matchedRules };
} }
@ -290,7 +291,7 @@
try { try {
frameInfo.frameSrc = window.location.href; frameInfo.frameSrc = window.location.href;
frameInfo.frameName = window.name || null; frameInfo.frameName = window.name || null;
} catch { /* cross-origin frame */ } } catch (e) { if (!(e instanceof DOMException)) throw e; }
} }
chrome.runtime.sendMessage({ chrome.runtime.sendMessage({
@ -347,7 +348,8 @@
function findElement(selector) { function findElement(selector) {
try { try {
return document.querySelector(selector); return document.querySelector(selector);
} catch { } catch (e) {
if (!(e instanceof TypeError) && !(e instanceof DOMException)) throw e;
return null; return null;
} }
} }

View File

@ -451,7 +451,8 @@ async function pollChat() {
// Show/hide stop button based on agent status // Show/hide stop button based on agent status
updateStopButton(data.agentStatus === 'processing'); updateStopButton(data.agentStatus === 'processing');
} catch (err) { } catch (err) {
console.error('[gstack sidebar] Chat poll error:', err.message); if (!err?.message?.includes('Failed to fetch') && !err?.message?.includes('The operation was aborted')) throw err;
console.debug('[gstack sidebar] Chat poll skipped (server unreachable)');
} finally { } finally {
pollInProgress = false; pollInProgress = false;
} }
@ -529,7 +530,8 @@ async function stopAgent() {
const resp = await fetch(`${serverUrl}/sidebar-agent/stop`, { method: 'POST', headers: authHeaders() }); const resp = await fetch(`${serverUrl}/sidebar-agent/stop`, { method: 'POST', headers: authHeaders() });
if (!resp.ok) console.warn(`[gstack sidebar] Stop agent failed: ${resp.status}`); if (!resp.ok) console.warn(`[gstack sidebar] Stop agent failed: ${resp.status}`);
} catch (err) { } catch (err) {
console.error('[gstack sidebar] Stop agent error:', err.message); if (!err?.message?.includes('Failed to fetch')) throw err;
console.debug('[gstack sidebar] Stop agent skipped (server unreachable)');
} }
// Immediately clean up UI // Immediately clean up UI
const thinking = document.getElementById('agent-thinking'); const thinking = document.getElementById('agent-thinking');
@ -598,7 +600,8 @@ async function pollTabs() {
renderTabBar(data.tabs); renderTabBar(data.tabs);
} catch (err) { } catch (err) {
console.error('[gstack sidebar] Tab poll error:', err.message); if (!err?.message?.includes('Failed to fetch') && !err?.message?.includes('The operation was aborted')) throw err;
console.debug('[gstack sidebar] Tab poll skipped (server unreachable)');
} }
} }
@ -646,7 +649,8 @@ async function switchBrowserTab(tabId) {
switchChatTab(tabId); switchChatTab(tabId);
pollTabs(); pollTabs();
} catch (err) { } catch (err) {
console.error('[gstack sidebar] Failed to switch browser tab:', err.message); if (!err?.message?.includes('Failed to fetch')) throw err;
console.debug('[gstack sidebar] Tab switch skipped (server unreachable)');
} }
} }
@ -658,7 +662,8 @@ document.getElementById('clear-chat').addEventListener('click', async () => {
const resp = await fetch(`${serverUrl}/sidebar-chat/clear`, { method: 'POST', headers: authHeaders() }); const resp = await fetch(`${serverUrl}/sidebar-chat/clear`, { method: 'POST', headers: authHeaders() });
if (!resp.ok) console.warn(`[gstack sidebar] Clear chat failed: ${resp.status}`); if (!resp.ok) console.warn(`[gstack sidebar] Clear chat failed: ${resp.status}`);
} catch (err) { } catch (err) {
console.error('[gstack sidebar] Clear chat error:', err.message); if (!err?.message?.includes('Failed to fetch')) throw err;
console.debug('[gstack sidebar] Clear chat skipped (server unreachable)');
} }
// Reset local state // Reset local state
chatLineCount = 0; chatLineCount = 0;
@ -690,7 +695,8 @@ document.getElementById('chat-cookies-btn').addEventListener('click', async () =
body: JSON.stringify({ command: 'goto', args: [`${serverUrl}/cookie-picker`] }), body: JSON.stringify({ command: 'goto', args: [`${serverUrl}/cookie-picker`] }),
}); });
} catch (err) { } catch (err) {
console.error('[gstack sidebar] Failed to open cookie picker:', err.message); if (!err?.message?.includes('Failed to fetch')) throw err;
console.debug('[gstack sidebar] Cookie picker skipped (server unreachable)');
} }
}); });