HookStackGitHub
Back to catalogue
WorkflowStopFailure

Log API errors to file

Appends every API error (rate limit, auth failure, billing, server error, etc.) to a persistent log file with timestamp, error type, details and session ID. Enables post-mortem analysis of failed sessions.

Use cases

  • Track frequency and type of API errors across sessions
  • Diagnose billing or authentication issues in CI/CD pipelines
  • Correlate API failures with specific session IDs for debugging

Providers & tags

Claude Code
#api-errors#logging#stop-failure#debugging#audit

settings.json fragment

{
  "hooks": {
    "StopFailure": [
      {
        "hooks": [
          {
            "command": "node $CLAUDE_PROJECT_DIR/.claude/hooks/stop-failure-log-api-errors.mjs",
            "type": "command"
          }
        ]
      }
    ]
  }
}

Script · .claude/hooks/stop-failure-log-api-errors.mjs

#!/usr/bin/env node
// Journalise les erreurs d'API à l'arrêt en échec (StopFailure)
import { readFileSync, appendFileSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

export function run(
  input,
  {
    append = appendFileSync,
    mkdir = mkdirSync,
    projectDir = process.env.CLAUDE_PROJECT_DIR ?? '.',
    now = () => new Date().toISOString(),
  } = {},
) {
  const logPath = join(projectDir, '.claude', 'api-errors.log');
  try { mkdir(dirname(logPath), { recursive: true }); } catch { /* exists */ }

  const line = `${now()} | ${input.error} | ${input.error_details ?? ''} | session:${input.session_id}\n`;
  append(logPath, line);
  return line;
}

/* v8 ignore next 4 */
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const input = JSON.parse(readFileSync(0, 'utf8'));
  run(input);
}