Error Handling and Testing Best Practices 🧪

Intermediate

In Go, explicit error handling is favored over exceptions. Functions often return an error type to indicate failure.

Error Handling

func readFile(filename string) ([]byte, error) {
    data, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return data, nil
}

// Usage
content, err := readFile("file.txt")
if err != nil {
    log.Fatal(err)
}

Writing Tests

Go provides a built-in testing framework. Create files ending with _test.go, then write test functions:

package main

import "testing"

func TestAdd(t *testing.T) {
    result := add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("Expected %d, got %d", expected, result)
    }
}

Run tests with:

go test

Robust testing and clear error handling lead to reliable software, crucial in production environments.