1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 // MyError is an error implementation that includes a time and message.
21 func (e MyError) Error() string {
22 return fmt.Sprintf("%v: %v", e.When, e.What)
27 time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
28 "the file system has gone away",
33 if err := oops(); err != nil {
36 // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
40 err := errors.New("emit macho dwarf: elf header corrupted")
44 // Output: emit macho dwarf: elf header corrupted
47 // The fmt package's Errorf function lets us use the package's formatting
48 // features to create descriptive error messages.
49 func ExampleNew_errorf() {
50 const name, id = "bimmler", 17
51 err := fmt.Errorf("user %q (id %d) not found", name, id)
55 // Output: user "bimmler" (id 17) not found
59 err1 := errors.New("err1")
60 err2 := errors.New("err2")
61 err := errors.Join(err1, err2)
63 if errors.Is(err, err1) {
64 fmt.Println("err is err1")
66 if errors.Is(err, err2) {
67 fmt.Println("err is err2")
77 if _, err := os.Open("non-existing"); err != nil {
78 if errors.Is(err, fs.ErrNotExist) {
79 fmt.Println("file does not exist")
86 // file does not exist
90 if _, err := os.Open("non-existing"); err != nil {
91 var pathError *fs.PathError
92 if errors.As(err, &pathError) {
93 fmt.Println("Failed at path:", pathError.Path)
100 // Failed at path: non-existing
103 func ExampleUnwrap() {
104 err1 := errors.New("error1")
105 err2 := fmt.Errorf("error2: [%w]", err1)
107 fmt.Println(errors.Unwrap(err2))