Go

Error Wrapping with %w

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`fmt.Errorf` with `%w` wraps an inner error inside an outer one, preserving the chain. Callers can use `errors.Is` / `errors.As` to inspect any level of the chain.
Go
Raw
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)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.