Go · lesson 11 of 30 · Decisions and loopsHandle errors
An error is a value you check at once. %w wraps the first error in a new one and errors.Is finds it there.
11-errors.go Download 11-errors.go
package main
import (
"errors"
"fmt"
"os"
)
var errEmpty = errors.New("the file is empty")
func size(name string) (int64, error) {
info, err := os.Stat(name)
if err != nil {
return 0, fmt.Errorf("size of %s: %w", name, err)
}
if info.Size() == 0 {
return 0, errEmpty
}
return info.Size(), nil
}
func main() {
for _, name := range []string{"words.txt", "missing.txt"} {
n, err := size(name)
if errors.Is(err, os.ErrNotExist) {
fmt.Println("no such file:", err)
os.Exit(1)
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(name, "has", n, "bytes")
}
}
Terminal
$ ./11-errors; echo "exit code $?"
words.txt has 87 bytes
no such file: size of missing.txt: stat missing.txt: no such file or directory
exit code 1Exercise
Report an empty file with its name.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.