HookStack
Back to catalogue
WorkflowStopFailure

Log API errors to file

Every API error logged for the post-mortem

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.

What does the Log API errors to file hook do?

Log API errors to file is a Claude Code StopFailure hook. It fires automatically at that lifecycle event — outside the model, so it can't be skipped or forgotten. Every API error logged for the post-mortem.

Because it is a deterministic Node.js script, it executes on every matching event without relying on the model to remember — the guarantee that makes agentic workflows safe to automate.

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

Tags

#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
// @hookstack stop-failure-log-api-errors
// Journalise les erreurs d'API à l'arrêt en échec (StopFailure)
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node: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);
}

Learn more

Related hooks