errors.As 解包为具体类型

版本新特性 / Go 1.13

type PathError struct {
    Path string
}

func (e *PathError) Error() string {
    return "path error: " + e.Path
}

err := fmt.Errorf("read config: %w", &PathError{Path: "/etc/app.conf"})

// *** before: ***
if pe, ok := err.(*PathError); ok {
    // will not match: err is now *fmt.wrapError, not *PathError
    fmt.Println(pe.Path)
}

// *** in version 1.13: ***
var pe *PathError
if errors.As(err, &pe) {
    fmt.Println(pe.Path)
}