package main
import (
"errors"
"fmt"
"os"
)
func loadConfig(path string) error {
_, err := os.Open(path)
if err != nil {
return fmt.Errorf("loadConfig: %w", err) // %w preserves the inner error
}
return nil
}
func main() {
err := loadConfig("/nope/missing.json")
fmt.Println(err)
// loadConfig: open /nope/missing.json: no such file or directory
// Check if the chain contains a specific sentinel
if errors.Is(err, os.ErrNotExist) {
fmt.Println("→ file did not exist (detected via errors.Is)")
}
// Extract a specific error type from the chain
var pathErr *os.PathError
if errors.As(err, &pathErr) {
fmt.Printf("→ path=%q op=%q\n", pathErr.Path, pathErr.Op)
}
}
Create a free account and build your private vault. Share publicly whenever you want.