Go errors.Is and fs.ErrNotExist
Open a receipt in a fresh workspace and handle the case where nobody has saved it yet.
A simple example
errors.Is and fs.ErrNotExist
- Start with No file named a.txt
- Do this Open a.txt for reading
- Result File missing
Syntax
errors.Is(err, fs.ErrNotExist)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goRecover when a receipt is missing
A clerk requests a receipt before a new folder contains any exports. Handle that missing entry explicitly so the application can give the clerk a useful next action.
package main
import (
"fmt"
"os"
"path/filepath"
"errors"
"io/fs"
)
func main() {
folder, err := os.MkdirTemp("", "receipts")
if err != nil { panic(err) }
defer os.RemoveAll(folder)
path := filepath.Join(folder, "today.txt")
data, err := os.ReadFile(path)
switch {
case errors.Is(err, fs.ErrNotExist):
fmt.Println("No receipt yet")
case err != nil:
panic(err)
default:
fmt.Println(string(data))
}
}
No receipt yet
The example deliberately uses an absent receipt. Permission failures and unrelated errors should still be visible.
Read a saved shift record
The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.
Handle an unsubmitted handover
The next shift opens an empty inbox before the first clerk submits a file. Open the expected file and show the desk whether it is available.
What to watch for
An existence check and a later open are separate operations. Handle failure at the point where the file is opened.