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.
Bạn sẽ học được gì
- Returning errors
- Wrapping with %w
- errors.Is and errors.As
findUser(id)
findUser(1)"Ada", nilfindUser(7)wrapped ErrNotFoundfindUser(-1)*ValidationErrorCheck 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
- nil means success.
- %w wraps an error with more context.
errors.Isfinds an error inside a wrapped one.
Ví dụ Go chạy được
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)
}
}
}
found Ada
missing: find user 7: user not found
bad input: idLuyệ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.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
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.
- Tuổi không hợp lệ đầu tiên Xác thực các tuổi đã nhập và báo vị trí của mục nhập sai đầu tiên thay vì để chương trình bị lỗi. Dễ
- Cộng các số hợp lệ Cộng các mục là số nguyên và bỏ qua mọi thứ khác, theo cách try/except xử lý dữ liệu đầu vào lỗi. Dễ