Struct và 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.

  • Trung cấp
  • Đọc trong 4 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

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

Ví dụ Go chạy được

Go
Chạy code →
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)
		}
	}
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
found Ada
missing: find user 7: user not found
bad input: id

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách