Tips & Tricks (Diperbarui: 2/6/2026)

Diagnosis Error dengan Claude Code: dari Log ke Regression Test

Workflow praktis Claude Code untuk diagnosis error, triage log, minimal repro, regression test, dan verifikasi.

Diagnosis Error dengan Claude Code: dari Log ke Regression Test

Diagnosis error bukan sekadar membaca baris merah terakhir di terminal lalu mengubah kode berdasarkan tebakan. Diagnosis yang baik mengubah kegagalan menjadi bukti yang bisa direproduksi oleh developer lain, test runner, atau Claude Code.

Ada tiga istilah dasar. Log adalah catatan dari command atau aplikasi. Stack trace adalah jalur pemanggilan fungsi yang mengarah ke error. Minimal reproduction adalah contoh terkecil yang tetap gagal setelah UI, data, dan konfigurasi yang tidak relevan dihapus.

Claude Code bekerja lebih baik jika Anda tidak hanya berkata “fix this”. Berikan command yang gagal, baris pertama yang relevan, beberapa hipotesis, dan command verifikasi yang harus lulus setelah perbaikan.

Bacaan terkait: Claude Code build error triage loop, Claude Code error message decoder, dan Claude Code bug report template.

Alur Diagnosis

flowchart LR
  A["Simpan command gagal"] --> B["Cari baris gagal pertama"]
  B --> C["Batasi tiga hipotesis"]
  C --> D["Buat minimal repro"]
  D --> E["Tambah regression test"]
  E --> F["Terapkan fix terkecil"]
  F --> G["Verifikasi dengan command sama"]
  G --> H["Tulis catatan handoff"]

Urutan ini mencegah pola berbahaya: edit dulu, bukti belakangan. Claude Code dapat membaca banyak file; instruksi yang terlalu luas bisa berubah menjadi refactor yang tidak relevan. Target diagnosis adalah mempersempit penyebab, bukan memperbanyak perubahan.

Kumpulkan empat bukti.

BuktiFungsiContoh untuk Claude Code
Command gagalMengunci reproduksinpm run build, node --test
Baris gagal pertamaMenghindari noise akhir logTypeError, ERR_MODULE_NOT_FOUND
Konteks runtimeMemisahkan bug lingkunganVersi Node.js, OS, CI
Perilaku yang diharapkanMendefinisikan fix benarnull menjadi array kosong, 404 tidak retry

Untuk nama error JavaScript, gunakan MDN JavaScript error reference. Untuk Node.js, Node.js Errors docs penting karena diagnosis stabil sebaiknya memakai error.code daripada teks pesan yang rapuh. Untuk E2E, Playwright debugging docs menjelaskan Inspector, Trace Viewer, dan debugging VS Code.

Workflow Praktis Claude Code

Gunakan prompt ini sebagai satu unit pekerjaan.

claude -p "
Diagnose the following error.

1. Confirm the failing command
2. Separate the first failure from unrelated log noise
3. List up to three root-cause hypotheses
4. Create a minimal reproduction
5. Add a regression test
6. Apply the smallest fix
7. Verify with the same command and write a handoff note

Constraints:
- Do not perform unrelated refactors
- Explain any public API change before making it
- Do not call the fix complete if verification still fails
"

“Maksimal tiga” sengaja dipilih. Sepuluh hipotesis sulit diverifikasi. Untuk Cannot read properties of undefined, biasanya cukup tiga kandidat: bentuk API berubah, nilai awal hilang, atau render terjadi sebelum data async siap.

Kasus 1: React undefined error

Kasus umum: API mengembalikan null, tetapi UI memanggil users.map(...). Ini tampak seperti masalah React, padahal akar masalahnya sering berupa kontrak bentuk data.

// user-list.mjs
export function names(users) {
  if (!Array.isArray(users)) {
    return [];
  }

  return users.map((user) => user.name ?? "(no name)");
}
// user-list.test.mjs
import assert from "node:assert/strict";
import test from "node:test";
import { names } from "./user-list.mjs";

test("names returns an empty array when the API returns null", () => {
  assert.deepEqual(names(null), []);
});

test("names keeps valid user names", () => {
  assert.deepEqual(names([{ name: "Masa" }]), ["Masa"]);
});
node --test user-list.test.mjs

Jika implementasi lama hanya return users.map(...), test pertama akan gagal. Minta Claude Code menambahkan failing test terlebih dahulu, lalu menerapkan perbaikan terkecil.

Kasus 2: ENOENT dan import failure di Node.js

ENOENT biasanya berarti file atau direktori tidak ditemukan. Jebakannya: config/local.json ada di laptop, tetapi tidak ada di CI atau image Docker.

Periksa command gagal, error.code, error.path, COPY di Dockerfile, .gitignore, dan working directory CI.

claude -p "
Diagnose this Node.js ENOENT failure.
Inspect error.code, error.path, current working directory, Dockerfile, and CI config.
Suggest only fixes that do not depend on a local-only file.
"

Jangan berhenti di “buat file yang hilang”. Jika konfigurasi wajib, fail lebih awal dengan pesan jelas. Jika opsional, beri default. Jika CI butuh contoh, copy file sample yang sudah masuk repo.

Kasus 3: Playwright gagal hanya di CI

Timeout Playwright bisa berasal dari bug aplikasi, wait condition salah, CI lambat, auth kedaluwarsa, atau jaringan berbeda. Menambah timeout sering hanya menyembunyikan penyebab.

Simpan trace saat gagal.

// playwright.config.ts
import { defineConfig } from "@playwright/test";

export default defineConfig({
  use: {
    screenshot: "only-on-failure",
    trace: "retain-on-failure",
    video: "retain-on-failure",
  },
});

Berikan Claude Code spec yang gagal, locator, state layar yang diharapkan, lokasi trace, dan command CI. Instruksinya: “sebelum menaikkan timeout, pisahkan state UI, respons API, autentikasi, dan masalah locator”.

Kasus 4: Error TypeScript berantai

Dua puluh error TypeScript tidak selalu berarti dua puluh bug. Satu perubahan tipe API bisa membuat banyak error turunan.

npx tsc --noEmit --pretty false 2>&1 | tee tsc.log
claude -p "
Read tsc.log and choose the first type error to fix.
Separate derived errors from the likely root cause.
After the fix, verify with npx tsc --noEmit --pretty false.
"

Jangan memperbaiki semuanya sekaligus. Perbaiki tipe akar, jalankan command yang sama, lalu lihat sisa error. Loop ini mengurangi patch as any yang tidak perlu.

Klasifikasikan log sebelum membaca semua

Script kecil ini bisa langsung dijalankan untuk memberi kategori awal.

// triage-log.mjs
import fs from "node:fs";

const sample = `
TypeError: Cannot read properties of undefined (reading 'map')
    at ProductList (src/ProductList.tsx:42:18)
`;

const input = process.argv[2]
  ? fs.readFileSync(process.argv[2], "utf8")
  : sample;

const rules = [
  [/ERR_MODULE_NOT_FOUND|Cannot find module/i, "dependency or import path"],
  [/ENOENT/i, "file path or working directory"],
  [/TypeError:.*undefined|Cannot read properties/i, "data shape or initial value"],
  [/Timeout.*expect|locator/i, "E2E wait condition or screen state"],
  [/TS\d{4}/, "TypeScript type error"],
];

const matches = rules
  .filter(([pattern]) => pattern.test(input))
  .map(([, label]) => label);

console.log(matches.length ? matches.join("\n") : "Unclassified: inspect first failure");
node triage-log.mjs
node triage-log.mjs tsc.log

Ini bukan pengganti diagnosis. Fungsinya hanya memisahkan dependency, path file, bentuk data, wait E2E, dan TypeScript error sebelum percakapan menjadi terlalu besar.

Template Bug Report yang Reproducible

Sebelum meminta investigasi, ubah bug menjadi format ini. Jika memakai GitHub Issues, syntax resmi GitHub issue forms bisa membuat field yang sama menjadi form.

## Summary
Describe the broken behavior in one sentence.

## Failed command
`npm run build`

## Expected result
The build succeeds and creates `dist/`.

## Actual result
The command fails with `TypeError: Cannot read properties of undefined`.

## First failing line
`src/components/ProductList.tsx:42:18`

## Reproduction steps
1. `npm ci`
2. `npm run build`

## Environment
- Node.js: 22.x
- OS: Windows 11 / GitHub Actions ubuntu-latest
- Branch: feature/product-list

## Already tried
- Regenerated lockfile
- Checked API response fixture

## Verification after fix
- `node --test`
- `npm run build`

Kalimat penting bukan “ada yang rusak”, tetapi “langkah ini mereproduksi kegagalan yang sama”.

Pitfall Umum

Pertama, hanya menempel baris terakhir log. Simpan baris gagal pertama dan konteks di sekitarnya.

Kedua, bergantung pada teks pesan error. Di Node.js, pakai error.code atau name jika tersedia.

Ketiga, melewati minimal reproduction. Di halaman penuh, sulit tahu apakah penyebab hilang atau hanya timing berubah.

Keempat, fix tanpa regression test. Bug yang sama bisa kembali saat refactor berikutnya.

Kelima, memberi Claude Code scope terlalu besar. Minta perubahan terkecil yang membuat failure spesifik ini lulus. Untuk batas review, lihat Claude Code review workflow checklist.

Tulis Catatan Handoff

Setelah verifikasi lulus, tinggalkan catatan pendek.

## Diagnosis note
- Failure: `npm run build`
- Cause: `users.map` was called when the API returned null
- Fix: Normalize non-array input to an empty array in `names()`
- Regression test: `node --test user-list.test.mjs`
- Verification: `npm run build` passed
- Remaining risk: Confirm separately whether API null is intentional
claude -p "
Write a Markdown diagnosis note for this fix.
Include cause, changed files, regression test, verification command,
and remaining risk. Keep it short enough for a reviewer to read in five minutes.
"

Template dan Konsultasi

Untuk proyek pribadi, command dan template di artikel ini sudah cukup. Untuk tim, tentukan log mana yang boleh dibagikan, secret apa yang tidak boleh ditempel ke Claude Code, lokasi minimal repro, artifact CI wajib, dan bukti apa yang diminta reviewer.

ClaudeCodeLab menyediakan produk dan template Claude Code serta training dan konsultasi Claude Code untuk tim yang ingin menstandarkan bug report, prompt triage CI, regression test, dan catatan handoff.

Saat workflow ini dipakai dalam maintenance ClaudeCodeLab, Masa melihat peningkatan terbesar dari tiga kebiasaan: menyimpan baris gagal pertama, membuat minimal reproduction, dan menjalankan command yang sama setelah fix. Saran Claude Code menjadi lebih mudah dipercaya karena selalu disertai evidence, hypothesis, test, dan hasil verifikasi.

#claude-code #debugging #error-diagnosis #workflow
Gratis

PDF gratis: cheatsheet Claude Code

Masukkan email dan unduh satu halaman berisi command, kebiasaan review, dan workflow aman.

Kami menjaga datamu dan tidak mengirim spam.

Masa

Tentang penulis

Masa

Engineer yang berfokus pada workflow Claude Code praktis dan adopsi tim.