Go:Go Error Handling: if err != nil, fmt.Errorf, and errors.Is
Go•Error Handling

Go Error Handling: if err != nil, fmt.Errorf, and errors.Is

Go treats errors as regular values. Functions return errors explicitly, checked via if err != nil.

Syntax

if err != nil { return fmt.Errorf("task failed: %w", err) }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
%wFormat VerbWraps an error in fmt.Errorf for inspection with errors.Is().

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import (
    "errors"
    "fmt"
)

var ErrNotFound = errors.New("record not found")

func findUser(id int) (string, error) {
    if id != 101 {
        return "", fmt.Errorf("query failed for id %d: %w", id, ErrNotFound)
    }
    return "dev_alex", nil
}

func main() {
    // 1. Success query
    user, err := findUser(101)
    if err == nil {
        fmt.Println("Found user:", user)
    }

    // 2. Failed query with errors.Is check
    _, err = findUser(999)
    if errors.Is(err, ErrNotFound) {
        fmt.Println("[CAUGHT] Verified target error:", err)
    }
}
Expected Output:
Found user: dev_alex
[CAUGHT] Verified target error: query failed for id 999: record not found

How It Works: Step-by-Step

  • Line 8: Declares sentinel error ErrNotFound.
  • Line 12: Wraps error using fmt.Errorf with %w.
  • Lines 25-27: errors.Is detects unwrapped sentinel error.

Key Concepts

  • In Go, errors are values of the built-in error interface (Error() string).
  • %w wraps errors to retain root cause identity.
  • errors.Is unwraps and compares error chains.

Common Mistake: Comparing wrapped errors with == instead of errors.Is

Wrapped errors created with %w are not equal to sentinel errors under ==. Always use errors.Is.

❌ Incorrect
if err == ErrNotFound { /* Fails if err is wrapped! */ }
✅ Correct
if errors.Is(err, ErrNotFound) { /* Correctly matches wrapped errors */ }

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler