Home > Blog > tech

Go Error Handling คืออะไร? Patterns และ Best Practices 2026

Go Error Handling คืออะไร? Patterns และ Best Practices 2026
2026-04-16 | tech | 3400 words

Error Handling ใน Go มีแนวทางที่แตกต่างจากภาษาอื่น Go ไม่มี try/catch แต่ใช้ explicit error return ทำให้ Code ชัดเจน บทความนี้สอนทุก Pattern ตั้งแต่พื้นฐานจนถึง Custom Error Types

Error ใน Go พื้นฐาน

// Go Error คือ Interface ที่มี Method Error() string
// ทุก Function ที่อาจผิดพลาดจะ Return error เป็น value สุดท้าย
// ตรวจสอบด้วย if err != nil
//
// Sentinel Errors: var ErrNotFound = errors.New("not found")
// ตรวจสอบด้วย errors.Is(err, ErrNotFound)
//
// Error Wrapping (Go 1.13+):
// return fmt.Errorf("reading config: %w", err)
// Unwrap ด้วย errors.Is() และ errors.As()
//
// Custom Error Types:
// สร้าง struct ที่ implement Error() string
// ใช้ errors.As() สำหรับ Type Assertion

Best Practices

Practiceคำอธิบาย
Handle errors immediatelyตรวจ err != nil ทันที
Wrap with contextใช้ fmt.Errorf + %w
Use errors.Is/Asไม่ใช้ == เปรียบเทียบ
Return earlyHandle error แล้ว return ทันที

สรุป

Go Error Handling ใช้ error return แทน exception ใช้ Sentinel Errors สำหรับค่าคงที่ Wrap Error ด้วย %w ใช้ Custom Error Types สำหรับข้อมูลเพิ่มเติม และตรวจสอบด้วย errors.Is/errors.As เสมอ


Back to Blog | iCafe Forex | SiamLanCard | Siam2R