Missing File Fallback With errors.Is And fs.ErrNotExist

Split read failures into expected and unexpected branches: fall back to defaults on fs.ErrNotExist and let other wrapped errors bubble up for the caller.

GoResilience

Code

gosnippet
32 lines
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)

// loadSettings 把读文件失败分成两类:缺文件是预期分支,回退默认配置;
// 其余错误(权限、IO)原样上抛并保留根因
func loadSettings(path string) ([]byte, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return []byte("workers=4\ntimeout=30s\n"), nil
		}
		return nil, fmt.Errorf("read %s: %w", path, err)
	}
	return data, nil
}

func main() {
	settings, err := loadSettings("app.dev.yaml")
	fmt.Printf("fallback: %q err=%v\n", string(settings), err)

	// errors.Is 穿透包装链:识别哨兵错误而不是比对错误字符串
	wrapped := fmt.Errorf("boot: %w", fs.ErrNotExist)
	fmt.Println("wrapped is not-exist:", errors.Is(wrapped, fs.ErrNotExist))
	permission := fmt.Errorf("boot: %w", fs.ErrPermission)
	fmt.Println("permission is not-exist:", errors.Is(permission, fs.ErrNotExist))
}

What the code does

Missing File Fallback With errors.Is And fs.ErrNotExist reduces to the functions loadSettings and main.

Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

What to watch for

  • error is part of the return tuple, so every caller decides what failure means.

Applying it

Entry signature: func loadSettings(path string) ([]byte, error)

Output lines are prefixed (fallback:, wrapped is not-exist:, permission is not-exist:), so the output keeps every step attributable.

Launch the file; main takes over and steps through loadSettings.

Statements that carry the weight

return nil, fmt.Errorf("read %s: %w", path, err)
permission := fmt.Errorf("boot: %w", fs.ErrPermission)
wrapped := fmt.Errorf("boot: %w", fs.ErrNotExist)

Interactive Tools for This Topic

FAQ

How should callers handle failures?
No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
What does Missing File Fallback With errors.Is And fs.ErrNotExist print when run?
No setup needed: run the file and look for labeled lines like `fallback:`, `wrapped is not-exist:`, `permission is not-exist:` in the output.