Skip to content
Hands-on IT IT Drills

Day 3: Error Handling and Modules – envcheck

Goal: Use sentinel errors, a custom error type, wrapping and errors.Is/As to build the tool envcheck, which checks whether tools, environment variables and ports are present – with your first real dependency · Duration: approx. 120 min · Prerequisite: Day 2

Briefing

  • Errors are values of type error, not an exception mechanism. Every function that can fail returns (…, error); the caller decides.
  • Sentinel errors (var ErrNotSet = errors.New(…)) are fixed values; check them with errors.Is.
  • Custom error types carry data (which check, which name); get them out with errors.As or – new in Go 1.26 – errors.AsType.
  • Wrapping with fmt.Errorf("kontext: %w", err) adds context without losing the cause. errors.Join collects several errors.
  • Dependencies are listed in go.mod (what) and go.sum (checksums); go mod tidy cleans up.
 run() ──► config.Load ──► "config envcheck.yaml: keine Checks konfiguriert"
   │                         └─ %w ─► ErrEmpty                      ⇒ Exit 2
   └─► check.Port ──► *check.Error{Kind:"port", Name:"127.0.0.1:8099"}
                         └─ Err ─► "nicht erreichbar (connect: refused)"
                                     ├─ %w ─► ErrUnreachable
                                     └─ %w ─► syscall.ECONNREFUSED  ⇒ Exit 1

Drill 1: Module and first dependency

mkdir -p ~/go-lab/tag03-envcheck && cd ~/go-lab/tag03-envcheck
go mod init example.com/envcheck
go get go.yaml.in/yaml/[email protected]
cat go.mod

Expected (shortened):

go: creating new go.mod: module example.com/envcheck
go: added go.yaml.in/yaml/v3 v3.0.5
module example.com/envcheck

go 1.26.9

require go.yaml.in/yaml/v3 v3.0.5 // indirect

Why? go.yaml.in/yaml/v3 is the version of the well-known gopkg.in/yaml.v3 that the YAML project continues to maintain. Always pin the version explicitly. // indirect is there because no code imports the package yet – go mod tidy fixes that in Drill 4.

Save your progress? Sign up for free

Drill 2: Sentinel errors and a custom error type

mkdir -p cmd/envcheck internal/check internal/config
cat > internal/check/errors.go <<'EOF'
// Package check checks tools, environment variables and ports.
package check

import (
    "errors"
    "fmt"
)

// Sentinel errors: fixed values, comparable with errors.Is.
var (
    ErrNotFound    = errors.New("nicht im PATH")
    ErrNotSet      = errors.New("nicht gesetzt")
    ErrUnreachable = errors.New("nicht erreichbar")
)

// Error is a failed check. errors.As gives you the fields.
type Error struct {
    Kind string // "tool", "env" or "port"
    Name string // e.g. "kubectl", "HOME", "127.0.0.1:8099"
    Err  error  // the cause, usually a sentinel
}

func (e *Error) Error() string {
    return fmt.Sprintf("%s %s: %v", e.Kind, e.Name, e.Err)
}

// Unwrap makes the cause visible to errors.Is and errors.As.
func (e *Error) Unwrap() error { return e.Err }
EOF
go vet ./...

Expected: no output.

Why? Every type with an Error() string method satisfies the error interface. Unwrap() tells errors.Is and errors.As where the chain continues. The receiver is a pointer, so *check.Error is the error type – you will need that again in a moment with errors.As. (The sentinel texts mean “not in PATH”, “not set” and “not reachable”.)

Save your progress? Sign up for free

Drill 3: The three checks

cat > internal/check/check.go <<'EOF'
package check

import (
    "errors"
    "fmt"
    "net"
    "os"
    "os/exec"
    "time"
)

// Tool looks up name in PATH and returns the path it found.
func Tool(name string) (string, error) {
    path, err := exec.LookPath(name)
    if err != nil {
        return "", &Error{Kind: "tool", Name: name, Err: ErrNotFound}
    }
    return path, nil
}

// Env checks whether the environment variable name is set and not empty.
func Env(name string) error {
    if os.Getenv(name) == "" {
        return &Error{Kind: "env", Name: name, Err: ErrNotSet}
    }
    return nil
}

// Port checks whether a service accepts TCP connections on addr (host:port).
func Port(addr string, timeout time.Duration) error {
    conn, err := net.DialTimeout("tcp", addr, timeout)
    if err != nil {
        // errors.As pulls the *net.OpError out of the chain; its Err is shorter.
        var opErr *net.OpError
        if errors.As(err, &opErr) {
            err = opErr.Err
        }
        // Two %w: sentinel AND cause both stay reachable for errors.Is.
        cause := fmt.Errorf("%w (%w)", ErrUnreachable, err)
        return &Error{Kind: "port", Name: addr, Err: cause}
    }
    return conn.Close()
}
EOF
go vet ./...

Expected: no output.

Why? fmt.Errorf with two %w (since Go 1.20) keeps both errors in the chain: later you can check for ErrUnreachable and for syscall.ECONNREFUSED. errors.As with a *net.OpError extracts only the short part of the message; without this step, dial tcp 127.0.0.1:8099: would appear twice in the output.

Save your progress? Sign up for free

Drill 4: Load the config with context

cat > internal/config/config.go <<'EOF'
// Package config loads the envcheck configuration from a YAML file.
package config

import (
    "bytes"
    "errors"
    "fmt"
    "io"
    "os"
    "time"

    "go.yaml.in/yaml/v3"
)

// ErrEmpty reports a configuration without a single check.
var ErrEmpty = errors.New("keine Checks konfiguriert")

// Config describes what must be present on the machine.
type Config struct {
    Tools   []string      `yaml:"tools"`
    Env     []string      `yaml:"env"`
    Ports   []string      `yaml:"ports"`
    Timeout time.Duration `yaml:"timeout"`
}

// Load reads path. Every error is wrapped with context (%w).
func Load(path string) (Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return Config{}, fmt.Errorf("config laden: %w", err)
    }
    var c Config
    dec := yaml.NewDecoder(bytes.NewReader(data))
    dec.KnownFields(true) // typos like "tool:" are errors
    if err := dec.Decode(&c); err != nil && !errors.Is(err, io.EOF) {
        return Config{}, fmt.Errorf("config %s: %w", path, err)
    }
    if len(c.Tools)+len(c.Env)+len(c.Ports) == 0 {
        return Config{}, fmt.Errorf("config %s: %w", path, ErrEmpty)
    }
    if c.Timeout <= 0 {
        c.Timeout = 2 * time.Second
    }
    return c, nil
}
EOF
go mod tidy
cat go.mod

Expected:

module example.com/envcheck

go 1.26.9

require go.yaml.in/yaml/v3 v3.0.5

Why? With %w, each layer adds only what it knows (“config laden” = “load config”, the file name) – the cause from os.ReadFile is preserved. KnownFields(true) turns a typo in the YAML into an error instead of a silent zero value. An empty file returns io.EOF; here that is not an error but leads to ErrEmpty.

Save your progress? Sign up for free

Drill 5: main – evaluate errors, choose the exit code

cat > cmd/envcheck/main.go <<'EOF'
// envcheck checks whether tools, environment variables and ports are present.
// Day 3 from "Go hands-on".
package main

import (
    "errors"
    "flag"
    "fmt"
    "io/fs"
    "os"

    "example.com/envcheck/internal/check"
    "example.com/envcheck/internal/config"
)

// Exit codes: 0 = all present, 1 = checks failed, 2 = invocation/config broken.
func main() {
    path := flag.String("config", "envcheck.yaml", "Pfad zur YAML-Konfiguration")
    flag.Parse()

    err := run(*path)
    if err == nil {
        return
    }
    var ce *check.Error
    if errors.As(err, &ce) { // at least one check failed
        if errors.Is(err, check.ErrNotSet) {
            fmt.Fprintln(os.Stderr, "Tipp: fehlende Variablen mit export setzen")
        }
        os.Exit(1)
    }
    fmt.Fprintln(os.Stderr, "envcheck:", err)
    if errors.Is(err, fs.ErrNotExist) {
        fmt.Fprintln(os.Stderr, "Tipp: envcheck.yaml anlegen oder -config nutzen")
    }
    os.Exit(2)
}

// run loads the config, runs all checks and prints a table.
// Failed checks are returned collected via errors.Join.
func run(path string) error {
    cfg, err := config.Load(path)
    if err != nil {
        return err
    }
    var errs []error
    for _, name := range cfg.Tools {
        where, err := check.Tool(name)
        errs = append(errs, line("tool", name, where, err))
    }
    for _, name := range cfg.Env {
        errs = append(errs, line("env", name, "gesetzt", check.Env(name)))
    }
    for _, addr := range cfg.Ports {
        err := check.Port(addr, cfg.Timeout)
        errs = append(errs, line("port", addr, "offen", err))
    }
    joined := errors.Join(errs...) // Join ignores nil entries
    if joined == nil {
        fmt.Printf("alle %d Checks bestanden\n", len(errs))
        return nil
    }
    failed := 0
    for _, err := range errs {
        if err != nil {
            failed++
        }
    }
    fmt.Printf("%d von %d Checks fehlgeschlagen\n", failed, len(errs))
    return joined
}

// line prints a result line and passes err through unchanged.
func line(kind, name, ok string, err error) error {
    mark, detail := "✔", ok
    // Go 1.26: errors.AsType is the generic variant of errors.As.
    if ce, isCheck := errors.AsType[*check.Error](err); isCheck {
        mark, detail = "✘", ce.Err.Error()
    }
    fmt.Printf("%s %-5s %-16s %s\n", mark, kind, name, detail)
    return err
}
EOF
cat > envcheck.yaml <<'EOF'
# envcheck.yaml – what this machine needs for the labs
tools: [go, git, kubectl, helm]
env: [HOME, KUBECONFIG]
ports: ["127.0.0.1:8099"]
timeout: 500ms
EOF
go build -o bin/envcheck ./cmd/envcheck
./bin/envcheck; echo "exit=$?"

Expected (paths and results depend on your machine):

✔ tool  go               /opt/homebrew/bin/go
✔ tool  git              /opt/homebrew/bin/git
✔ tool  kubectl          /opt/homebrew/bin/kubectl
✔ tool  helm             /opt/homebrew/bin/helm
✔ env   HOME             gesetzt
✘ env   KUBECONFIG       nicht gesetzt
✘ port  127.0.0.1:8099   nicht erreichbar (connect: connection refused)
2 von 7 Checks fehlgeschlagen
Tipp: fehlende Variablen mit export setzen
exit=1

Why? main is thin: run returns an error, main turns it into an exit code. errors.As finds the first *check.Error even through errors.Join – so you know “checks failed” (1) rather than “invocation broken” (2). errors.Is(err, check.ErrNotSet) searches the same chain for the sentinel. In line you see errors.AsType: same effect, but without a variable declared beforehand. (The output reads “set”, “open”, “2 of 7 checks failed” and “Tip: set missing variables with export”.)

Save your progress? Sign up for free

Drill 6: Reading error chains

Now the error paths. Each message shows the chain from the outside in:

./bin/envcheck -config nope.yaml; echo "exit=$?"
printf 'tool: [go]\n' > typo.yaml
./bin/envcheck -config typo.yaml; echo "exit=$?"
: > leer.yaml
./bin/envcheck -config leer.yaml; echo "exit=$?"
printf 'tools: [go]\ntimeout: zwei\n' > bad.yaml
./bin/envcheck -config bad.yaml; echo "exit=$?"
rm typo.yaml leer.yaml bad.yaml

Expected:

envcheck: config laden: open nope.yaml: no such file or directory
Tipp: envcheck.yaml anlegen oder -config nutzen
exit=2
envcheck: config typo.yaml: yaml: unmarshal errors:
  line 1: field tool not found in type config.Config
exit=2
envcheck: config leer.yaml: keine Checks konfiguriert
exit=2
envcheck: config bad.yaml: yaml: unmarshal errors:
  line 2: cannot unmarshal !!str `zwei` into time.Duration
exit=2

Why? The tip for nope.yaml comes from errors.Is(err, fs.ErrNotExist): underneath your wrapping sits the *fs.PathError from os.ReadFile, and its cause counts as fs.ErrNotExist. Never compare error texts with strings.Contains; texts change, sentinels and types don’t.

Tip: A timeout case to try out: ports: ["10.255.255.1:443"] with timeout: 300ms yields nicht erreichbar (i/o timeout) – the address never answers.

Save your progress? Sign up for free

Drill 7: Maintain and verify modules

go list -m all
go mod why go.yaml.in/yaml/v3
go mod verify
cat go.sum
go run golang.org/x/vuln/cmd/[email protected] ./...

Expected:

example.com/envcheck
go.yaml.in/yaml/v3 v3.0.5
# go.yaml.in/yaml/v3
example.com/envcheck/internal/config
go.yaml.in/yaml/v3
all modules verified
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
No vulnerabilities found.
Command What for
go list -m all all modules in the build, including transitive ones
go mod why <modul> which of your packages pulls it in
go mod verify check the cache contents against go.sum
govulncheck ./... known CVEs – only if the code actually calls the function

Why? go.sum contains checksums; Go also compares the values against the public checksum database sum.golang.org. Anyone who tampers with a module after the fact gets caught. go.mod and go.sum both belong in Git.

Save your progress? Sign up for free

Drill 8: The tool is done

A service on port 8099 and a variable that is set – then everything has to be green:

cd ~/go-lab/tag03-envcheck
python3 -m http.server 8099 --bind 127.0.0.1 >/dev/null 2>&1 &
sleep 1
KUBECONFIG=~/.kube/config ./bin/envcheck; echo "exit=$?"
kill %1

Expected:

✔ tool  go               /opt/homebrew/bin/go
✔ tool  git              /opt/homebrew/bin/git
✔ tool  kubectl          /opt/homebrew/bin/kubectl
✔ tool  helm             /opt/homebrew/bin/helm
✔ env   HOME             gesetzt
✔ env   KUBECONFIG       gesetzt
✔ port  127.0.0.1:8099   offen
alle 7 Checks bestanden
exit=0

Your module:

tag03-envcheck/
├── cmd/envcheck/main.go          run(), exit codes, output
├── internal/check/errors.go      sentinels, *check.Error
├── internal/check/check.go       Tool, Env, Port
├── internal/config/config.go     load YAML, wrapping
├── envcheck.yaml
├── go.mod
└── go.sum

Tip: envcheck works well as the first step in Makefiles and CI jobs: instead of cryptic errors in the middle of the build, you see right at the start what is missing. You can use it to pre-check the labs of the coming days.

Save your progress? Sign up for free

Checkpoint

#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/go-lab/tag03-envcheck
check "gofmt sauber" "test -z \"\$(gofmt -l .)\""
check "go vet" "go vet ./..."
check "golangci-lint" "~/go-lab/bin/lint run ./..."
check "go.mod aufgeräumt" "go mod tidy -diff"
check "Prüfsummen ok" "go mod verify"
check "Exit 1 bei fehlendem Port" \
  "printf 'ports: [\"127.0.0.1:1\"]\n' > /tmp/ec.yaml;
   ./bin/envcheck -config /tmp/ec.yaml; test \$? -eq 1"
check "Exit 2 ohne Config" "./bin/envcheck -config /nix.yaml; test \$? -eq 2"
rm -f /tmp/ec.yaml

Expected:

✔ gofmt sauber
✔ go vet
✔ golangci-lint
✔ go.mod aufgeräumt
✔ Prüfsummen ok
✔ Exit 1 bei fehlendem Port
✔ Exit 2 ohne Config

go mod tidy -diff changes nothing; it only reports whether tidy would change something – ideal for CI.

Challenge

Write a second command waitport in the same module: it waits until a port is open (waitport -timeout 10s 127.0.0.1:8099) and prints “noch zu” (“still closed”) on every refused attempt. Reuse check.Port and detect “connection refused” without comparing text.

Hint: Thanks to the two %w in check.Port, syscall.ECONNREFUSED is in the error chain.

Solution

mkdir -p cmd/waitport
cat > cmd/waitport/main.go <<'EOF'
// waitport waits until a TCP port is open – for example before integration tests.
package main

import (
    "errors"
    "flag"
    "fmt"
    "os"
    "syscall"
    "time"

    "example.com/envcheck/internal/check"
)

func main() {
    timeout := flag.Duration("timeout", 10*time.Second, "maximale Wartezeit")
    flag.Parse()
    if flag.NArg() != 1 {
        fmt.Fprintln(os.Stderr, "Aufruf: waitport [-timeout 10s] host:port")
        os.Exit(2)
    }
    addr := flag.Arg(0)
    deadline := time.Now().Add(*timeout)
    for {
        err := check.Port(addr, time.Second)
        if err == nil {
            fmt.Println("offen:", addr)
            return
        }
        if time.Now().After(deadline) {
            fmt.Fprintln(os.Stderr, "waitport:", err)
            os.Exit(1)
        }
        // The chain of Day 3 errors reaches all the way to the syscall error.
        if errors.Is(err, syscall.ECONNREFUSED) {
            fmt.Println("noch zu, neuer Versuch ...")
        }
        time.Sleep(500 * time.Millisecond)
    }
}
EOF
go build -o bin/waitport ./cmd/waitport
(sleep 1; python3 -m http.server 8099 --bind 127.0.0.1 >/dev/null 2>&1) &
./bin/waitport 127.0.0.1:8099; echo "exit=$?"
pkill -f 'http.server 8099'
./bin/waitport -timeout 1s 127.0.0.1:8099; echo "exit=$?"

Expected (the number of attempts varies):

noch zu, neuer Versuch ...
noch zu, neuer Versuch ...
noch zu, neuer Versuch ...
offen: 127.0.0.1:8099
exit=0
noch zu, neuer Versuch ...
noch zu, neuer Versuch ...
waitport: port 127.0.0.1:8099: nicht erreichbar (connect: connection refused)
exit=1

Two commands share one internal package – that is the reason for the cmd/<tool> plus internal/ layout. The timeout variant (i/o timeout) does not count as “refused” and runs silently until the deadline. On Day 15 (challenge portwait) you replace the loop with context.WithTimeout and backoff.

Save your progress? Sign up for free

Enterprise Note

  • Error messages are interfaces: context in (which file, which host), secrets out. Never put tokens, passwords or complete connection strings into fmt.Errorf.
  • Document exit codes and keep them stable; pipelines and operators rely on them.
  • Set GOPROXY, GOPRIVATE and GONOSUMDB for internal modules; in air-gapped environments use go mod vendor or an internal proxy.
  • govulncheck belongs in every CI pipeline, and Renovate or Dependabot update dependencies – with go mod tidy -diff as the gate.
  • Check licenses before a dependency comes in (e.g. with go-licenses); some customers forbid (A)GPL in the shipped binary.