2.2 Structured Error Responses
Structured Error Responses คืออะไร
เมื่อ tool เกิด error สิ่งที่ return กลับไปให้ Claude มีผลมากต่อว่า agent จะ recover ได้ดีแค่ไหน — ถ้า error message ชัดเจนและ structured Claude สามารถตัดสินใจได้ว่าควร retry, ใช้ tool อื่น, หรือแจ้ง user ได้ถูกต้อง
หลักการคือ: tool result ที่เป็น error ควรบอก Claude 3 อย่าง: (1) error เกิดจากอะไร (2) recoverable หรือไม่ (3) ถ้า recoverable ควรทำอะไร
Error Response Structure
def execute_tool(name, input):
try:
result = run_tool_logic(name, input)
return {"type": "tool_result", "content": json.dumps(result)}
except ToolError as e:
error_response = {
"error_code": e.code,
"error_type": e.type, # "validation", "not_found", "rate_limit", "internal"
"message": e.message,
"recoverable": e.recoverable,
"suggestion": e.suggestion # "retry after 5s", "use different query"
}
return {
"type": "tool_result",
"content": json.dumps(error_response),
"is_error": True
}
Error Categories
Retryable Errors
Claude สามารถ retry ได้ทันที:
- Rate limiting (429) → retry after delay
- Timeout → retry with simpler query
- Temporary unavailability → retry later
Recoverable Errors
Claude ต้องเปลี่ยน approach:
- Validation error → fix input parameters
- Not found → try different search term
- Permission denied → use alternative tool
Fatal Errors
Claude ต้องหยุดและแจ้ง user:
- Service permanently down
- Authentication expired
- Data corruption
is_error Flag
Messages API มี is_error: true flag สำหรับ tool results ที่เป็น error:
# Tool result ปกติ
{"type": "tool_result", "tool_use_id": "xyz", "content": "Success"}
# Tool result ที่เป็น error
{"type": "tool_result", "tool_use_id": "xyz", "content": "File not found: config.yml", "is_error": true}
เมื่อ is_error: true — Claude จะรู้ว่า tool ล้มเหลว และจะพิจารณาว่าควรทำอะไรต่อ (retry, use another tool, or inform user)
Best Practices
- Error message ควร actionable — บอก Claude ว่าทำอะไรต่อได้
- อย่า return stack traces — Claude ไม่ต้องการ implementation details
- ใช้ consistent error format ทุก tools — Claude เรียนรู้ pattern ได้
- Include relevant context — เช่น “User ‘abc’ not found in database ‘users’”
Exam Tips
is_error: trueบอก Claude ว่า tool call ล้มเหลว — Claude จะปรับ strategy- Error ที่ recoverable ควรบอกวิธี fix — เช่น “Try searching with a broader term”
- ข้อสอบอาจถามว่า error response แบบไหนดีกว่า — เลือกที่มี error type + suggestion
- อย่า return raw exception messages — ไม่ helpful สำหรับ Claude