Struct และ Interface

Go Error Handling: errors.Is and errors.As

Errors are values in Go. Return them, add context with %w, and check them the right way.

  • ระดับกลาง
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Returning errors
  • Wrapping with %w
  • errors.Is and errors.As
findUser(id)
findUser(1)"Ada", nil
findUser(7)wrapped ErrNotFound
findUser(-1)*ValidationError

Check the error, then continue

Go has no exceptions for ordinary failures. A function that can fail returns an error as its last value, and the caller checks whether it is nil.

ErrNotFound is a fixed error value that callers can compare against. %w wraps it with more context, and errors.Is still finds it inside the wrapped error. ValidationError is an error type with its own data, and errors.As extracts it.

ประเด็นสำคัญ

  1. nil means success.
  2. %w wraps an error with more context.
  3. errors.Is finds an error inside a wrapped one.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import (
	"errors"
	"fmt"
)

var ErrNotFound = errors.New("user not found")

type ValidationError struct {
	Field string
}

func (e *ValidationError) Error() string {
	return "invalid " + e.Field
}

func findUser(id int) (string, error) {
	if id <= 0 {
		return "", &ValidationError{Field: "id"}
	}
	if id != 1 {
		return "", fmt.Errorf("find user %d: %w", id, ErrNotFound)
	}
	return "Ada", nil
}

func main() {
	for _, id := range []int{1, 7, -1} {
		name, err := findUser(id)
		var validation *ValidationError
		switch {
		case err == nil:
			fmt.Println("found", name)
		case errors.Is(err, ErrNotFound):
			fmt.Println("missing:", err)
		case errors.As(err, &validation):
			fmt.Println("bad input:", validation.Field)
		}
	}
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
found Ada
missing: find user 7: user not found
bad input: id

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Bank Account with Errors →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด