Debug với Claude Code — Từ error message đến root cause trong 5 phút
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Nghiên cứu cho thấy developer dành trung bình 35-50% thời gian làm việc cho debugging.
- 2 Dùng git blame: Khi cần hiểu tại sao code được viết theo cách gây lỗi, yêu cầu Claude Code check git history.
- 3 Tìm cách fix đúng đắn nhất theo TypeScript best practices.
- 4 Khoảng 2% requests bị timeout (deadline exceeded) sau 5 giây.
- 5 QUAN TRỌNG: Logging phải có thể tắt bằng env variable DEBUG_CART=true để không ảnh hưởng performance khi không cần debug.
Debugging là kỹ năng tiêu tốn nhiều thời gian nhất của developer. Nghiên cứu cho thấy developer dành trung bình 35-50% thời gian làm việc cho debugging. Claude Code thay đổi hoàn toàn quy trình này: bạn paste error message, Claude Code đọc stack trace, hiểu codebase context, truy ngược đến root cause, và đề xuất fix cụ thể. Bài viết này hướng dẫn debug workflow hoàn chỉnh với Claude Code, từ các lỗi đơn giản đến debugging production issues phức tạp.
Debug workflow cốt lõi
Quy trình debug với Claude Code gồm 4 bước:
- Paste error: Copy error message hoặc stack trace vào Claude Code
- Trace: Claude Code đọc stack trace, xác định file và dòng code gây lỗi
- Analyze: Claude Code phân tích ngữ cảnh xung quanh, hiểu logic flow, tìm root cause
- Fix: Claude Code đề xuất fix, giải thích tại sao fix này giải quyết root cause, và có thể apply fix trực tiếp
Ví dụ thực tế: TypeError
# Paste error vào Claude Code:
TypeError: Cannot read properties of undefined (reading 'map')
at UserList (/src/components/UserList.tsx:15:28)
at renderWithHooks (/node_modules/react-dom/cjs/react-dom.development.js:14985:18)
at mountIndeterminateComponent (/node_modules/react-dom/cjs/react-dom.development.js:17811:13)
Claude Code sẽ tự động:
- Mở file
/src/components/UserList.tsxdòng 15 - Đọc component code và hiểu data flow
- Xác định rằng
usersprop chưa được truyền hoặc API chưa trả về data khi component render - Đề xuất fix: thêm optional chaining, default value, hoặc loading state
Các pattern lỗi phổ biến và prompt templates
1. Import/Module errors
Lỗi phổ biến nhất khi setup project hoặc upgrade dependencies:
# Prompt template cho import errors
Tôi gặp lỗi import sau:
ModuleNotFoundError: No module named 'pydantic_settings'
File: /app/config.py, line 3
Python version: 3.11
pip list output:
pydantic==2.6.0
Đây là nội dung file config.py:
[paste file content]
Tìm root cause và fix. Kiểm tra xem có breaking change
trong phiên bản pydantic tôi đang dùng không.
Claude Code sẽ nhận ra rằng từ Pydantic v2, module pydantic_settings đã được tách ra thành package riêng pydantic-settings, cần cài đặt thêm.
2. Async/Await errors
Lỗi async là một trong những lỗi khó debug nhất vì stack trace thường không phản ánh đúng execution flow:
# Prompt template cho async errors
Tôi gặp lỗi async sau:
RuntimeWarning: coroutine 'fetch_user_data' was never awaited
fetch_user_data(user_id)
Sau đó:
TypeError: 'coroutine' object is not subscriptable
Đây là code gây lỗi:
async def get_user_profile(user_id):
user_data = fetch_user_data(user_id) # line 45
return user_data["name"] # line 46
async def fetch_user_data(user_id):
async with aiohttp.ClientSession() as session:
response = await session.get(f"/api/users/{user_id}")
return await response.json()
Debug và fix lỗi này. Giải thích tại sao lỗi xảy ra.
Claude Code sẽ xác định thiếu await ở dòng 45 và giải thích cơ chế coroutine trong Python.
3. Database connection errors
# Prompt template cho DB errors
Lỗi kết nối database trong production:
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "db.internal" and accepting
TCP/IP connections on port 5432?
Context:
- Ứng dụng chạy trên Docker container
- Database là PostgreSQL trên RDS
- Lỗi xảy ra ngẫu nhiên, khoảng 5% requests
- Connection pool size: 20
- Concurrent users: khoảng 200
Environment:
- DATABASE_URL: postgresql://user:***@db.internal:5432/mydb
- Dùng SQLAlchemy với pool_size=20, max_overflow=10
Debug: tại sao lỗi chỉ xảy ra ngẫu nhiên?
Kiểm tra connection pool configuration.
Đề xuất fix và monitoring.
Claude Code sẽ phân tích rằng với 200 concurrent users nhưng pool chỉ có 20 + 10 overflow = 30 connections, có thể xảy ra connection exhaustion. Đề xuất tăng pool, thêm connection timeout, retry logic, và health check.
4. Type errors trong TypeScript
# Prompt template cho TypeScript type errors
TypeScript compilation errors:
error TS2345: Argument of type 'string | undefined' is not
assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
45 | const userId = searchParams.get("userId");
46 | const userData = await fetchUser(userId);
~~~~~~
File: /src/pages/api/user.ts
Không muốn dùng type assertion (as string).
Tìm cách fix đúng đắn nhất theo TypeScript best practices.
5. Race condition errors
# Prompt template cho race conditions
Bug report: Đôi khi số dư tài khoản bị sai sau khi
2 transactions chạy đồng thời.
Trước: balance = 1,000,000
Transaction A: rút 300,000
Transaction B: rút 500,000
Expected: balance = 200,000
Actual (sometimes): balance = 500,000 hoặc 700,000
Code xử lý transaction:
[paste code]
Database: PostgreSQL
ORM: Prisma
Đây có phải race condition không?
Phân tích step-by-step execution flow khi 2 transactions chạy đồng thời.
Đề xuất fix dùng database-level locking.
Debug production issues
Production debugging có những thách thức riêng: không thể attach debugger, phải dựa vào logs, và cần minimize downtime.
Log analysis với Claude Code
# Prompt template cho log analysis
Phân tích log file production sau đây và tìm root cause
cho lỗi 500 error spike lúc 14:30 hôm nay:
[paste relevant log entries]
Thông tin bổ sung:
- Ứng dụng: Node.js Express API
- Infrastructure: 3 instances trên ECS behind ALB
- Trước 14:30 mọi thứ hoạt động bình thường
- 14:25 có deployment mới (version 2.3.1 -> 2.3.2)
- 14:30 error rate tăng từ 0.1% lên 15%
- 14:45 rollback về 2.3.1, error rate về 0.1%
Phân tích:
1. Correlation giữa deployment và error spike
2. Root cause trong version 2.3.2
3. Tại sao không phát hiện trong staging
4. Prevention measures
Performance profiling
# Prompt template cho performance debugging
API endpoint GET /api/products tốn 3-5 giây thay vì < 200ms.
Thông tin:
- Database query: SELECT * FROM products
JOIN categories ON ... WHERE ...
- EXPLAIN ANALYZE output:
[paste explain output]
- Bảng products: 500,000 rows
- Bảng categories: 200 rows
- Không có index nào ngoài primary key
Code hiện tại:
[paste code]
Phân tích:
1. Bottleneck ở đâu? (Query? Network? Serialization?)
2. Cần thêm index nào?
3. Query có thể tối ưu không?
4. Cần pagination không?
5. Caching strategy?
Debug workflow nâng cao với Claude Code
Bisect debugging
Khi bug xuất hiện nhưng không rõ commit nào gây ra:
Bug: Feature X không hoạt động. Nó hoạt động đúng ở version 2.1.0
nhưng lỗi ở version 2.3.0.
Giúp tôi dùng git bisect để tìm commit gây lỗi:
1. Hướng dẫn cách setup git bisect
2. Viết test script để tự động verify bug
3. Phân tích commit gây lỗi khi tìm được
Memory leak debugging
Ứng dụng Node.js bị memory leak. Heap tăng dần từ 200MB
lên 1.2GB trong 24 giờ rồi crash (OOM killed).
Heap snapshot diff (taken at 1h and 4h after start):
[paste snapshot summary]
Nghi ngờ liên quan đến:
- Event listeners không được remove
- Closure giữ reference đến large objects
- Cache không có TTL
Code nghi ngờ gây leak:
[paste code]
Phân tích heap snapshot và xác định nguồn leak.
Đề xuất fix và cách verify leak đã được fix.
Distributed system debugging
Lỗi intermittent trong microservices architecture:
Service A gọi Service B qua gRPC.
Khoảng 2% requests bị timeout (deadline exceeded) sau 5 giây.
Logs Service A:
[paste logs]
Logs Service B:
[paste logs]
Tracing data (OpenTelemetry):
- Trace ID: abc123
- Service A -> Service B: 5002ms (timeout)
- Service B internal processing: 150ms
- Service B response sent: 152ms
Tại sao Service B xử lý xong trong 150ms nhưng
Service A vẫn bị timeout? Debug network layer.
CLAUDE.md configuration cho debug workflow
# CLAUDE.md - Debug section
## Debugging
- Khi gặp error, luôn đọc TOÀN BỘ stack trace trước khi suggest fix
- Trace ngược từ error location đến root cause, không fix symptoms
- Check git blame để xem ai và khi nào sửa code liên quan gần nhất
- Với production errors, kiểm tra recent deployments và config changes
- Luôn viết regression test sau khi fix bug
- Không silent catch errors: log đầy đủ context
## Common error patterns
- ImportError: Check requirements.txt/package.json version
- TypeError: Check null/undefined, API response shape
- ConnectionError: Check env vars, network, DNS, firewall
- PermissionError: Check file permissions, IAM roles
Xây dựng debug prompt library
Sau một thời gian debug với Claude Code, bạn sẽ nhận ra một số prompt patterns hiệu quả. Lưu chúng lại để tái sử dụng:
Quick debug prompt
Lỗi: [paste error]
File: [file path]
Context: [mô tả ngắn đang làm gì]
1. Root cause là gì?
2. Fix nhanh nhất?
3. Fix đúng đắn nhất?
4. Cần viết test gì để prevent regression?
Deep debug prompt
Bug report: [mô tả bug]
Reproduce steps: [các bước reproduce]
Expected: [expected behavior]
Actual: [actual behavior]
Environment: [OS, runtime, versions]
Đọc các files liên quan và phân tích:
1. Execution flow step-by-step
2. Tại sao actual khác expected
3. Root cause (không phải symptom)
4. Fix với giải thích
5. Regression test
6. Có chỗ nào khác trong codebase có bug tương tự không?
Production incident prompt
INCIDENT: [mô tả incident]
Impact: [số users affected, duration]
Timeline:
- [timestamp] [event]
- [timestamp] [event]
Logs: [paste relevant logs]
Metrics: [error rate, latency, etc.]
Recent changes: [deployments, config changes]
Phân tích:
1. Root cause
2. Immediate mitigation
3. Long-term fix
4. Post-mortem action items
Systematic error pattern analysis
Thay vì debug từng lỗi rời rạc, bạn có thể yêu cầu Claude Code phân tích pattern lỗi trên toàn bộ codebase để phòng ngừa trước khi lỗi xảy ra trong production.
Phân tích null/undefined patterns
Quét toàn bộ /src và tìm tất cả các chỗ có thể gây
TypeError: Cannot read properties of undefined/null:
1. Biến nhận giá trị từ API response nhưng không check null
2. Object destructuring không có default values
3. Array methods (map, filter, reduce) trên biến
có thể undefined
4. Optional chaining thiếu ở chain dài (a.b.c.d)
5. Async function returns có thể undefined khi error
Với mỗi pattern tìm được:
- File và dòng code
- Risk level (High nếu trên critical path)
- Fix đề xuất
- Tổng hợp: bao nhiêu chỗ cần fix, ưu tiên fix cái nào trước
Error handling audit
Kiểm tra toàn bộ error handling trong /src:
1. Try/catch blocks: catch có log đầy đủ context không?
Hay chỉ catch(e) rồi bỏ qua?
2. Promise: có .catch() hoặc try/catch cho mọi await không?
3. Express middleware: lỗi có được forward tới
error handler middleware không?
4. External API calls: có timeout và retry logic không?
5. Database operations: có handle connection errors không?
Liệt kê tất cả "silent failures" — chỗ lỗi bị nuốt
mà không log hoặc không thông báo cho caller.
Dependency vulnerability scan
Đọc package.json (hoặc requirements.txt) và phân tích:
1. Dependencies nào đã deprecated hoặc unmaintained?
2. Có version conflicts giữa các dependencies không?
3. Dependencies nào có known security vulnerabilities?
4. Có dependencies nào quá nặng cho chức năng đang dùng?
(ví dụ: import cả lodash chỉ để dùng _.get)
Đề xuất thay thế hoặc upgrade cho từng issue.
Debug với breakpoints và conditional logging
Khi stack trace không đủ thông tin, Claude Code giúp thêm logging có mục đích vào đúng chỗ:
Bug: Giỏ hàng đôi khi tính sai tổng tiền.
Không reproduce được consistently.
Thêm conditional logging vào /src/services/cart.service.ts:
1. Log chi tiết mỗi lần calculate_total() được gọi
2. Log input data (items, quantities, prices)
3. Log intermediate calculations
4. Log final result
5. Thêm assertion: nếu total < 0 hoặc total != sum(items),
log ERROR với full stack trace
Format log: JSON structured logging, bao gồm
request_id, user_id, timestamp, và cart state.
QUAN TRỌNG: Logging phải có thể tắt bằng env variable
DEBUG_CART=true để không ảnh hưởng performance khi
không cần debug.
Debug frontend-backend integration
Một category lỗi khó debug là mismatch giữa frontend expectations và backend responses:
Bug: Frontend hiển thị "undefined" cho tên sản phẩm.
API response thực tế:
{
"data": {
"product_name": "Áo thun basic",
"price": 250000
}
}
Frontend code đang đọc:
const name = response.data.name; // undefined!
const price = response.data.price;
Phân tích:
1. So sánh API response schema với frontend interface/type
2. Tìm tất cả mismatches giữa field names
3. Ai đúng — frontend type hay backend response?
4. Đề xuất: thêm API contract testing (zod schema hoặc
OpenAPI validation) để catch mismatches sớm
5. Fix immediate: đổi frontend hay backend?
Debug environment-specific issues
Lỗi chỉ xảy ra ở production nhưng không reproduce được ở local là loại lỗi gây frustration nhất:
Bug: API hoạt động bình thường ở local nhưng trả về
403 Forbidden ở production.
Checklist debug:
1. So sánh environment variables (local vs production)
2. So sánh node/python version
3. Kiểm tra CORS configuration
4. Kiểm tra API gateway / reverse proxy rules
5. Kiểm tra SSL/TLS certificates
6. Kiểm tra firewall / security group rules
7. Kiểm tra IAM roles và permissions
8. Kiểm tra database connectivity và credentials
9. Kiểm tra DNS resolution
10. Kiểm tra container image version
Với mỗi item, gợi ý command cụ thể để verify.
Ví dụ: curl -v để check headers, env | grep để check vars.
# Commands để debug environment differences
# Check env vars (redact sensitive values)
env | grep -E "(DATABASE|API_KEY|SECRET|PORT|HOST)" | sed 's/=.*/=***REDACTED***/'
# Check DNS resolution
nslookup api.internal.service
# Check connectivity
curl -v --connect-timeout 5 https://api.example.com/health
# Check SSL certificate
openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null | openssl x509 -noout -dates
# Check container runtime
docker inspect --format '{{.Config.Image}}' container_name
Debug multi-file issues
Nhiều bug không nằm trong một file duy nhất mà là kết quả của interaction giữa nhiều modules. Claude Code xử lý tốt vì có khả năng đọc toàn bộ codebase:
Bug: User registration thành công nhưng không nhận được email xác nhận.
Các files liên quan:
- /src/controllers/auth.controller.ts (xử lý registration)
- /src/services/user.service.ts (tạo user trong DB)
- /src/services/email.service.ts (gửi email)
- /src/queues/email.queue.ts (email queue processor)
- /src/config/email.config.ts (SMTP configuration)
Đọc tất cả files trên và trace execution flow từ
registration request đến email delivery.
Xác định chỗ nào email bị "nuốt" mà không có error.
Claude Code sẽ đọc tất cả files, trace flow, và có thể phát hiện rằng email queue processor bắt lỗi nhưng chỉ log ở debug level (không hiện trong production logs), hoặc SMTP config thiếu biến môi trường nhưng code fallback thầm lặng.
Tips debug hiệu quả với Claude Code
- Cung cấp đủ context: Error message + file path + những gì bạn đang cố làm. Càng nhiều context, Claude Code tìm root cause càng nhanh.
- Đừng chỉ paste error: Thêm thông tin: khi nào lỗi bắt đầu, có thay đổi gì gần đây không, lỗi có xảy ra 100% hay intermittent.
- Yêu cầu giải thích: Đừng chỉ nhận fix rồi apply. Hỏi "tại sao lỗi này xảy ra" để hiểu và phòng tránh trong tương lai.
- Viết regression test: Sau mỗi bug fix, yêu cầu Claude Code viết test để đảm bảo bug không quay lại.
- Check toàn codebase: Hỏi "có chỗ nào khác trong codebase có cùng pattern bug này không?" để fix tất cả occurrences.
- Dùng git blame: Khi cần hiểu tại sao code được viết theo cách gây lỗi, yêu cầu Claude Code check git history.
Tổng kết
Debug với Claude Code không chỉ nhanh hơn mà còn giáo dục hơn. Mỗi lần debug, bạn học được cách Claude Code trace lỗi, phân tích root cause, và đề xuất fix. Qua thời gian, bạn sẽ nội hóa những pattern này và trở thành debugger giỏi hơn -- có hoặc không có AI. Bắt đầu bằng việc paste error messages vào Claude Code thay vì Google. So sánh kết quả. Bạn sẽ nhận ra Claude Code không chỉ tìm fix nhanh hơn, mà fix cũng chính xác hơn vì nó hiểu codebase context mà Google hay Stack Overflow không thể có.
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.






