PPysolate SpineREAD THE CODE · UNDERSTAND THE SYSTEM
课程与章节
源码索引 / CURRENT IMPLEMENTATION

learning/go-patterns/patterns/errors/errors.go

44 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。

跳到函数 / 声明
// Package errors demonstrates sentinel categories, wrapping, and typed details.
package errors

import (
	"errors"
	"fmt"
)

// ErrNotFound is the stable category callers can inspect with errors.Is.
var ErrNotFound = errors.New("item not found")

// NotFoundError carries the key that was not present while remaining in the
// ErrNotFound category.
type NotFoundError struct {
	Key string
}

// Error implements error.
func (e *NotFoundError) Error() string {
	return fmt.Sprintf("item %q not found", e.Key)
}

// Unwrap makes errors.Is and errors.As work through wrapping layers.
func (e *NotFoundError) Unwrap() error {
	return ErrNotFound
}

// Lookup finds a value or returns a typed, classifiable not-found error.
func Lookup(items map[string]string, key string) (string, error) {
	value, ok := items[key]
	if !ok {
		return "", &NotFoundError{Key: key}
	}
	return value, nil
}

// Load adds operation context while preserving the underlying error identity.
func Load(items map[string]string, key string) (string, error) {
	value, err := Lookup(items, key)
	if err != nil {
		return "", fmt.Errorf("load %q: %w", key, err)
	}
	return value, nil
}