fix: resolve all 301 error handling anti-patterns across codebase

Systematic cleanup of every error handling anti-pattern detected by the
automated scanner. 289 issues fixed via code changes, 12 approved with
specific technical justifications.

Changes across 90 files:
- GENERIC_CATCH (141): Added instanceof Error type discrimination
- LARGE_TRY_BLOCK (82): Extracted helper methods to narrow try scope to ≤10 lines
- NO_LOGGING_IN_CATCH (65): Added logger/console calls for error visibility
- CATCH_AND_CONTINUE_CRITICAL_PATH (10): Added throw/return or approved overrides
- ERROR_STRING_MATCHING (2): Approved with rationale (no typed error classes)
- ERROR_MESSAGE_GUESSING (1): Replaced chained .includes() with documented pattern array
- PROMISE_CATCH_NO_LOGGING (1): Added logging to .catch() handler

Also fixes a detector bug where nested try/catch inside a catch block
corrupted brace-depth tracking, causing false positives.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Alex Newman
2026-04-19 19:57:00 -07:00
parent c9adb1c77b
commit a0dd516cd5
91 changed files with 4846 additions and 3414 deletions
+2 -2
View File
@@ -31,7 +31,7 @@ export function writeAgentsMd(agentsPath: string, context: string): void {
try {
writeFileSync(tempFile, finalContent);
renameSync(tempFile, agentsPath);
} catch (error) {
logger.error('AGENTS_MD', 'Failed to write AGENTS.md', { agentsPath }, error as Error);
} catch (error: unknown) {
logger.error('AGENTS_MD', 'Failed to write AGENTS.md', { agentsPath }, error instanceof Error ? error : new Error(String(error)));
}
}
+37 -34
View File
@@ -439,47 +439,50 @@ export async function updateFolderClaudeMdFiles(
// Process each folder
for (const folderPath of folderPaths) {
let response: Response;
try {
// Fetch timeline via existing API (uses socket or TCP automatically)
const response = await workerHttpRequest(
response = await workerHttpRequest(
`/api/search/by-file?filePath=${encodeURIComponent(folderPath)}&limit=${limit}&project=${encodeURIComponent(project)}&isFolder=true`
);
if (!response.ok) {
logger.error('FOLDER_INDEX', 'Failed to fetch timeline', { folderPath, status: response.status });
continue;
}
const result = await response.json();
if (!result.content?.[0]?.text) {
logger.debug('FOLDER_INDEX', 'No content for folder', { folderPath });
continue;
}
const formatted = formatTimelineForClaudeMd(result.content[0].text);
// Fix for #794: Don't create new context files if there's no activity
// But update existing ones to show "No recent activity" if they already exist
const claudeMdPath = path.join(folderPath, targetFilename);
const hasNoActivity = formatted.includes('*No recent activity*');
const fileExists = existsSync(claudeMdPath);
if (hasNoActivity && !fileExists) {
logger.debug('FOLDER_INDEX', 'Skipping empty context file creation', { folderPath, targetFilename });
continue;
}
writeClaudeMdToFolder(folderPath, formatted, targetFilename);
logger.debug('FOLDER_INDEX', 'Updated context file', { folderPath, targetFilename });
} catch (error) {
} catch (error: unknown) {
// Fire-and-forget: log warning but don't fail
const err = error as Error;
logger.error('FOLDER_INDEX', `Failed to update ${targetFilename}`, {
const message = error instanceof Error ? error.message : String(error);
const stack = error instanceof Error ? error.stack : undefined;
logger.error('FOLDER_INDEX', `Failed to fetch timeline for ${targetFilename}`, {
folderPath,
errorMessage: err.message,
errorStack: err.stack
errorMessage: message,
errorStack: stack
});
continue;
}
if (!response.ok) {
logger.error('FOLDER_INDEX', 'Failed to fetch timeline', { folderPath, status: response.status });
continue;
}
const result = await response.json() as { content?: Array<{ text?: string }> };
if (!result.content?.[0]?.text) {
logger.debug('FOLDER_INDEX', 'No content for folder', { folderPath });
continue;
}
const formatted = formatTimelineForClaudeMd(result.content[0].text);
// Fix for #794: Don't create new context files if there's no activity
// But update existing ones to show "No recent activity" if they already exist
const claudeMdPath = path.join(folderPath, targetFilename);
const hasNoActivity = formatted.includes('*No recent activity*');
const fileExists = existsSync(claudeMdPath);
if (hasNoActivity && !fileExists) {
logger.debug('FOLDER_INDEX', 'Skipping empty context file creation', { folderPath, targetFilename });
continue;
}
writeClaudeMdToFolder(folderPath, formatted, targetFilename);
logger.debug('FOLDER_INDEX', 'Updated context file', { folderPath, targetFilename });
}
}
+2 -2
View File
@@ -21,7 +21,7 @@ export function readJsonSafe<T>(filePath: string, defaultValue: T): T {
if (!existsSync(filePath)) return defaultValue;
try {
return JSON.parse(readFileSync(filePath, 'utf-8'));
} catch (error) {
throw new Error(`Corrupt JSON file, refusing to overwrite: ${filePath}`);
} catch (error: unknown) {
throw new Error(`Corrupt JSON file, refusing to overwrite: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
+14 -9
View File
@@ -60,9 +60,9 @@ class Logger {
// Create log file path with date
const date = new Date().toISOString().split('T')[0];
this.logFilePath = join(logsDir, `claude-mem-${date}.log`);
} catch (error) {
// If log file initialization fails, just log to console
console.error('[LOGGER] Failed to initialize log file:', error);
} catch (error: unknown) {
// [ANTI-PATTERN IGNORED]: Logger cannot log its own failures, using stderr/console as last resort
console.error('[LOGGER] Failed to initialize log file:', error instanceof Error ? error.message : String(error));
this.logFilePath = null;
}
}
@@ -84,8 +84,9 @@ class Logger {
} else {
this.level = LogLevel.INFO;
}
} catch (error) {
// Fallback to INFO if settings can't be loaded
} catch (error: unknown) {
// [ANTI-PATTERN IGNORED]: Logger cannot log its own failures, using stderr/console as last resort
console.error('[LOGGER] Failed to load log level from settings:', error instanceof Error ? error.message : String(error));
this.level = LogLevel.INFO;
}
}
@@ -152,8 +153,12 @@ class Logger {
if (typeof toolInput === 'string') {
try {
input = JSON.parse(toolInput);
} catch {
} catch (_parseError: unknown) {
// [ANTI-PATTERN IGNORED]: Logger cannot log its own failures, using stderr/console as last resort
// Input is a raw string (e.g., Bash command), use as-is
if (_parseError instanceof Error) {
console.error('[logger] JSON parse failed for tool input:', _parseError);
}
input = toolInput;
}
}
@@ -289,10 +294,10 @@ class Logger {
if (this.logFilePath) {
try {
appendFileSync(this.logFilePath, logLine + '\n', 'utf8');
} catch (error) {
// Logger can't log its own failures - use stderr as last resort
} catch (error: unknown) {
// [ANTI-PATTERN IGNORED]: Logger cannot log its own failures, using stderr/console as last resort
// This is expected during disk full / permission errors
process.stderr.write(`[LOGGER] Failed to write to log file: ${error}\n`);
process.stderr.write(`[LOGGER] Failed to write to log file: ${error instanceof Error ? error.message : String(error)}\n`);
}
} else {
// If no log file available, write to stderr as fallback
+2 -1
View File
@@ -63,8 +63,9 @@ export function isProjectExcluded(projectPath: string, exclusionPatterns: string
if (regex.test(normalizedProjectPath)) {
return true;
}
} catch {
} catch (error: unknown) {
// Invalid pattern, skip it
console.warn(`[project-filter] Invalid exclusion pattern "${pattern}":`, error instanceof Error ? error.message : String(error));
continue;
}
}
+7 -3
View File
@@ -38,8 +38,11 @@ export function detectWorktree(cwd: string): WorktreeInfo {
let stat;
try {
stat = statSync(gitPath);
} catch {
// No .git at all - not a git repo
} catch (error: unknown) {
// No .git at all - not a git repo (ENOENT is expected, other errors are noteworthy)
if (error instanceof Error && (error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn(`[worktree] Unexpected error checking .git:`, error);
}
return NOT_A_WORKTREE;
}
@@ -52,7 +55,8 @@ export function detectWorktree(cwd: string): WorktreeInfo {
let content: string;
try {
content = readFileSync(gitPath, 'utf-8').trim();
} catch {
} catch (error: unknown) {
console.warn(`[worktree] Failed to read .git file:`, error instanceof Error ? error.message : String(error));
return NOT_A_WORKTREE;
}