Go Snippet

Idiomatic Go Error Handling

Difficulty: Easy

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.

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

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.