0Pricing
Go Academy · Lesson

The error Interface

Returning and checking errors idiomatically

The error Interface is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Go's Error Philosophy

Go handles errors as values, not exceptions. Functions return an error as the last return value. The caller must check it explicitly:

package main
import ("fmt"; "strconv")

func main() {
    n, err := strconv.Atoi("abc")
    if err != nil {
        fmt.Println("error:", err)  // handle it
        return
    }
    fmt.Println(n)
}

The error Interface

The built-in error is a simple interface:

// Built into Go — no import needed
type error interface {
    Error() string
}

// Any type with Error() string satisfies it
// nil means no error

Returning Errors

Functions that can fail return (value, error). Return nil for no error:

package main
import ("fmt"; "errors")

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(result)
}

The if err != nil Pattern

The if err != nil check is the most common Go idiom. Always handle errors — do not ignore them:

package main
import ("fmt"; "os")

func main() {
    f, err := os.Open("config.json")
    if err != nil {
        fmt.Println("open error:", err)
        return
    }
    defer f.Close()
    // use f...
    _ = f
}

errors.New — Simple Error Values

errors.New creates a simple error with a fixed message:

package main
import ("fmt"; "errors")

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

func findByID(id int) (string, error) {
    data := map[int]string{1: "Alice"}
    v, ok := data[id]
    if !ok {
        return "", ErrNotFound
    }
    return v, nil
}

func main() {
    _, err := findByID(99)
    fmt.Println(err) // not found
}

fmt.Errorf — Formatted Error Messages

fmt.Errorf creates errors with context from formatted strings:

package main
import "fmt"

func openConfig(path string) error {
    // Add context to the error message
    return fmt.Errorf("openConfig %s: file not found", path)
}

func main() {
    err := openConfig("/etc/app/config.yaml")
    fmt.Println(err)
    // openConfig /etc/app/config.yaml: file not found
}

Sentinel Errors

Sentinel errors are package-level error values used for identity comparison:

package main
import ("fmt"; "errors")

var (
    ErrTimeout    = errors.New("timeout")
    ErrPermission = errors.New("permission denied")
)

func doRequest() error { return ErrTimeout }

func main() {
    err := doRequest()
    if errors.Is(err, ErrTimeout) {
        fmt.Println("request timed out — retrying")
    }
}

Ignoring Errors Is a Bug

Go requires you to use every declared variable — but ignoring errors with _ compiles fine and is a common mistake to avoid:

package main
import "os"

func bad() {
    os.Remove("temp.txt") // silently ignores error — bad practice
}

func good() error {
    if err := os.Remove("temp.txt"); err != nil {
        return err  // propagate
    }
    return nil
}

Error Context: Adding Information

When propagating errors up the call stack, add context describing what operation failed:

package main
import "fmt"

func readConfig(path string) ([]byte, error) {
    return nil, fmt.Errorf("readConfig: %w", fmt.Errorf("file %s not found", path))
}

func setup() error {
    _, err := readConfig("/etc/app.cfg")
    if err != nil {
        return fmt.Errorf("setup: %w", err) // wrap with context
    }
    return nil
}

func main() {
    err := setup()
    fmt.Println(err) // setup: readConfig: file /etc/app.cfg not found
}

Multiple Error Returns

Functions may return errors from multiple failure points. Check each one:

package main
import ("fmt"; "strconv")

func parseRange(minStr, maxStr string) (int, int, error) {
    min, err := strconv.Atoi(minStr)
    if err != nil { return 0, 0, fmt.Errorf("min: %w", err) }
    max, err := strconv.Atoi(maxStr)
    if err != nil { return 0, 0, fmt.Errorf("max: %w", err) }
    if min > max { return 0, 0, fmt.Errorf("min %d > max %d", min, max) }
    return min, max, nil
}

func main() {
    lo, hi, err := parseRange("1", "10")
    if err != nil { fmt.Println(err); return }
    fmt.Println(lo, hi)
}

Quick Check

What does a nil error return value signify in Go?

Recap: The error Interface

Key error handling concepts:

  • Error is a built-in interface: Error() string
  • Return (value, error) — nil means success
  • errors.New for simple errors, fmt.Errorf for formatted errors
  • Always check if err != nil
  • Add context when propagating errors up the stack
  • Never silently ignore errors

Frequently asked questions

Is the “The error Interface” lesson free?

Yes — the full text of “The error Interface” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “The error Interface”?

Returning and checking errors idiomatically You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “The error Interface” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The error Interface
  2. Creating Custom Errors
  3. Error Wrapping and Unwrapping
  4. panic, recover and defer
← Back to Go Academy