Skip to content
Sessions & Workflows Intermediate

Handle Resume Failures

Gracefully fall back to a new session when --resume fails with an expired or corrupted ID

Command

"color:#9CA3AF;font-style:italic"># See JS code "color:#7C5CFC">for the full pattern

Response

// Success: resumed session data
// Failure: new session created as fallback

Parsing Code

059669">">function resumeOrNew(prompt, sessionId) {
  059669">">try {
    059669">">if (sessionId) {
      059669">">const out = execFileSync(059669059669">">'claude', [
        059669059669">">'-p', prompt, 059669059669">">'--resume', sessionId, 059669059669">">'--output-format', 059669059669">">'json'
      ], { encoding: 059669059669">">'utf-8', timeout: 120_000, env: { ...process.env, CLAUDECODE: 059669059669">">'' } });
      059669">">const data = JSON.parse(out);
      059669">">if (data.is_error) 059669">">throw 059669">">new Error(data.result);
      059669">">return data;
    }
  } 059669">">catch (err) {
    059669">">console.warn(059669">`Session ${sessionId} failed, starting 059669">">new`);
  }
  059669">">return JSON.parse(execFileSync(059669059669">">'claude', [
    059669059669">">'-p', prompt, 059669059669">">'--output-format', 059669059669">">'json'
  ], { encoding: 059669059669">">'utf-8', timeout: 120_000, env: { ...process.env, CLAUDECODE: 059669">'' } }));
}

Gotchas

! Expired or corrupted session IDs cause --resume to fail silently
! Always implement a fallback to start a fresh session

Related Recipes