-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.go
More file actions
41 lines (33 loc) · 713 Bytes
/
Copy pathreader.go
File metadata and controls
41 lines (33 loc) · 713 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// An example of wrapping and unwrapping errors in Go to provide
// better error tracing.
package main
import (
"errors"
"fmt"
"os"
)
type FileError struct {
Message string
}
func (e *FileError) Error() string {
return e.Message
}
func readFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
// Return the wrapped error
return fmt.Errorf("readFile: %w", &FileError{Message: "file not found"})
}
defer file.Close()
return nil
}
func main() {
if err := readFile("nonexistent.txt"); err != nil {
fmt.Println("Error:", err)
var fileErr *FileError
// Check if the error is of type FileError
if errors.As(err, &fileErr) {
fmt.Println(fileErr.Message)
}
}
}