os.ErrNotExist
GoERRORCommonFilesystem
no such file or directory
Quick Answer
Use errors.Is(err, os.ErrNotExist) to detect and handle a missing file.
What this means
Returned when an OS call fails because the file or path does not exist. Wrap with fmt.Errorf to add context.
Why it happens
- 1File path does not exist on disk
- 2Incorrect working directory at runtime
Fix
Check with errors.Is
Check with errors.Is
if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
log.Printf("missing: %s", p)
}Why this works
errors.Is unwraps the error chain to match the sentinel value.
Code examples
Detectgo
f, err := os.Open("x.txt")
if errors.Is(err, os.ErrNotExist) {
fmt.Println("not found")
}Create if missinggo
f, _ := os.OpenFile("x.txt",
os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()Wrap errorgo
if err != nil {
return fmt.Errorf("load config: %w", err)
}Same error in other languages
Sources
Official documentation ↗
Go standard library
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev