os.ErrExist
GoERRORNotableFilesystem
file already exists
Quick Answer
Use errors.Is(err, os.ErrExist) to skip creation when the file already exists.
What this means
Returned when an OS operation fails because the target file or directory already exists. Common with os.Mkdir and exclusive creates.
Why it happens
- 1Creating a file with os.O_EXCL when it already exists
- 2Calling os.Mkdir on an existing directory path
Fix
Guard with errors.Is
Guard with errors.Is
err := os.Mkdir("dir", 0755)
if err != nil && !errors.Is(err, os.ErrExist) {
log.Fatal(err)
}Why this works
Ignoring os.ErrExist allows idempotent directory creation.
Code examples
Detectgo
err := os.Mkdir("out", 0755)
if errors.Is(err, os.ErrExist) {
fmt.Println("already exists")
}MkdirAll avoids errorgo
// MkdirAll never returns ErrExist
err := os.MkdirAll("a/b/c", 0755)Exclusive creatego
f, err := os.OpenFile("lock",
os.O_CREATE|os.O_EXCL, 0600)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