Code Snippets
/

Idiomatic Go Error Handling

Idiomatic Go Error Handling

Go has no exceptions; errors are values returned alongside the result. This snippet covers the canonical `if err != nil` check, error wrapping with `fmt.Errorf("...: %w", err)` (Go 1.13+) for context, and unwrapping with `errors.Is` / `errors.As` to inspect underlying error types. Get this right and your stack of error returns will read as cleanly as any try/catch.

Go
Easy
3 snippets
go-error-handling
error-handling
implementation

1,090 views

7

package main

import (
    "errors"
    "fmt"
    "strconv"
)

func parsePositive(s string) (int, error) {
    n, err := strconv.Atoi(s)
    if err != nil {
        return 0, err
    }
    if n <= 0 {
        return 0, errors.New("value must be positive")
    }
    return n, nil
}

func main() {
    for _, s := range []string{"42", "-3", "abc"} {
        n, err := parsePositive(s)
        if err != nil {
            fmt.Printf("%s -> err: %v\n", s, err)
            continue
        }
        fmt.Printf("%s -> ok: %d\n", s, n)
    }
}

Every fallible operation returns (value, error). The caller checks err != nil immediately and either handles the error or returns it up the stack. There is no exception machinery to short-circuit the stack, which makes control flow obvious at the cost of more typing. errors.New("text") builds a plain error; fmt.Errorf("context: %v", inner) includes the inner error's message but loses the type, while the %w verb (next accordion) preserves the original for unwrapping. Always handle errors at the layer that has enough context to make a meaningful decision; do not blanket-log-and-continue.