Step Over to Go Part 9 of 50
  1. 1 Goodbye .csproj, Hello go.mod
  2. 2 The Phrasebook: C# Concepts in Go Terms
  3. 3 You Know .NET, Now Meet the Go Toolchain
  4. 4 No Enums? No Problem (Sort Of)
  5. 5 Generics: Late to the Party
  6. 6 The Million Dollar Mistake, Differently
  7. 7 Your Class Is Now a Struct (And That's Fine)
  8. 8 Where Did My Properties Go?
  9. 9 if err != nil: Your New Reality
  10. 10 Panic and Recover: The Emergency Exit
  11. 11 The switch Statement You Always Wanted
  12. 12 Stack vs Heap: Go's Escape Analysis
  13. 13 Pointers Without the Pain
  14. 14 Slices Are Not Arrays (And Neither Is List<T>)
  15. 15 Channels: The sync You Didn't Know You Wanted
  16. 16 Context Is King
  17. 17 Async/Await vs Goroutines: A Mindset Shift
  18. 18 select: Multiplexing Like a Pro
  19. 19 Mutexes and WaitGroups: When Channels Aren't the Answer
  20. 20 The Empty Interface and Type Assertions
  21. 21 Composition Over Inheritance (For Real This Time)
  22. 22 Implicit Interfaces: Scary Then Brilliant
  23. 23 Benchmarks and Profiling Out of the Box
  24. 24 Mocking in a Language Without Mockito
  25. 25 Multi-Module Repos: Monorepo Thinking
  26. 26 Organising a Real Project
  27. 27 Testing Without a Framework
  28. 28 Configuration Without IOptions<T>
  29. 29 Database Access: database/sql vs Entity Framework
  30. 30 Debugging: Delve vs Visual Studio's Comfort
  31. 31 Generate All the Things
  32. 32 GORM and Friends: When You Do Want an ORM
  33. 33 HTTP Services: net/http vs ASP.NET Core
  34. 34 JSON: Struct Tags and the Marshal Dance
  35. 35 Linting and Formatting: gofmt Is Non-Negotiable
  36. 36 Logging: slog and the Structured Logging Story
  37. 37 Shrinking Binaries and Build Tags
  38. 38 Dockerfile for Go: Simpler Than You'd Think
  39. 39 GitHub Actions for Go Projects
  40. 40 Health Checks and Readiness Probes
  41. 41 Kubernetes and Go: A Natural Fit
  42. 42 AWS Lambda and Go: Cold Starts That Don't Hurt
  43. 43 Metrics, Traces, and Logs: The OpenTelemetry Way
  44. 44 Single Binary Deploys: The Killer Feature
  45. 45 Versioning Your Modules
  46. 46 What I Actually Miss From C#
  47. 47 What I'll Never Go Back For
  48. 48 Six Months In: Was It Worth It?
  49. 49 Forty-Eight Posts on Moving From C# to Go, in the Right Order
  50. 50 Range-Over-Func Iterators for People Who Miss LINQ
About this series

if err != nil: Your New Reality

Let's address the elephant in the room. You're going to write if err != nil hundreds of times. Thousands, probably. And for the first week, you're going to hate it.

Coming from C#, where exceptions handle the sad path invisibly, Go's explicit error handling feels like a step backwards. It's verbose. It's repetitive. It clutters your code with what looks like boilerplate.

Then something shifts. You start to see what you're gaining. Let's work through that shift.

Why No Exceptions?

C# uses exceptions for error handling:

try
{
    var data = await File.ReadAllTextAsync("config.json");
    var config = JsonSerializer.Deserialize<Config>(data);
    await database.Connect(config.ConnectionString);
}
catch (FileNotFoundException)
{
    logger.Error("Config file missing");
}
catch (JsonException ex)
{
    logger.Error($"Invalid config: {ex.Message}");
}
catch (Exception ex)
{
    logger.Error($"Unexpected error: {ex.Message}");
    throw;
}

This looks clean. The happy path is uncluttered. Errors are handled elsewhere.

But there's a hidden cost: you can't see which lines can fail. Any line might throw. Any function you call might throw. The catch block is disconnected from the code that caused the problem.

Go takes the opposite view: errors are values, returned like any other value:

data, err := os.ReadFile("config.json")
if err != nil {
    return fmt.Errorf("reading config: %w", err)
}

var config Config
if err := json.Unmarshal(data, &config); err != nil {
    return fmt.Errorf("parsing config: %w", err)
}

if err := database.Connect(config.ConnectionString); err != nil {
    return fmt.Errorf("connecting to database: %w", err)
}

Verbose? Yes. But look at what you can see:

  • Every line that can fail is marked with err := or , err
  • You know exactly what error each block handles
  • The handling is right next to the call that produced the error
  • No hidden control flow. The code does what it looks like it does

The Error Interface

In Go, error is just an interface:

type error interface {
    Error() string
}

Anything with an Error() method is an error. This is intentionally simple.

Creating errors:

import "errors"

// Simple error
err := errors.New("something went wrong")

// Formatted error
err := fmt.Errorf("failed to load user %d: %w", userID, originalErr)

That %w verb is important. It wraps the original error, preserving the chain.

The Pattern You'll Write Forever

Here's the basic pattern:

result, err := doSomething()
if err != nil {
    return fmt.Errorf("doing something: %w", err)
}
// use result

Variations:

// When there's no result to use
if err := doSomething(); err != nil {
    return err
}

// When you want to handle specific errors
if err := doSomething(); err != nil {
    if errors.Is(err, ErrNotFound) {
        return defaultValue, nil  // handle gracefully
    }
    return zero, err  // propagate others
}

// When you need to clean up on error
file, err := os.Create("output.txt")
if err != nil {
    return err
}
defer file.Close()

if err := writeData(file); err != nil {
    os.Remove("output.txt")  // clean up partial file
    return fmt.Errorf("writing data: %w", err)
}

Wrapping Errors Properly

Go 1.13 introduced error wrapping. Use it:

// BAD: loses the original error
if err != nil {
    return errors.New("failed to connect")
}

// BAD: concatenates as string, loses error chain
if err != nil {
    return fmt.Errorf("failed to connect: %s", err)
}

// GOOD: wraps the error, preserves the chain
if err != nil {
    return fmt.Errorf("failed to connect: %w", err)
}

The %w verb creates a chain that can be inspected:

if errors.Is(err, sql.ErrNoRows) {
    // somewhere in the chain, there's a sql.ErrNoRows
}

var pathErr *os.PathError
if errors.As(err, &pathErr) {
    // somewhere in the chain, there's a *os.PathError
    fmt.Println(pathErr.Path)
}

Sentinel Errors

For errors that callers need to check, define package-level sentinel errors:

package user

var (
    ErrNotFound     = errors.New("user not found")
    ErrInvalidEmail = errors.New("invalid email address")
    ErrDuplicate    = errors.New("user already exists")
)

func Find(id string) (*User, error) {
    // ...
    if notFound {
        return nil, ErrNotFound
    }
    // ...
}

Callers can check:

user, err := user.Find("123")
if errors.Is(err, user.ErrNotFound) {
    // handle not found specifically
}

Custom Error Types

When you need more context, create a custom error type:

type ValidationError struct {
    Field   string
    Message string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("%s: %s", e.Field, e.Message)
}

func ValidateUser(u *User) error {
    if u.Email == "" {
        return &ValidationError{Field: "email", Message: "required"}
    }
    if !strings.Contains(u.Email, "@") {
        return &ValidationError{Field: "email", Message: "invalid format"}
    }
    return nil
}

Callers can extract details:

if err := ValidateUser(u); err != nil {
    var valErr *ValidationError
    if errors.As(err, &valErr) {
        fmt.Printf("Validation failed on %s: %s\n", valErr.Field, valErr.Message)
    }
}

Strategies That Help

Early Returns

Embrace early returns. Don't nest error handling:

// BAD: nested, hard to follow
func process() error {
    data, err := loadData()
    if err == nil {
        parsed, err := parseData(data)
        if err == nil {
            result, err := transform(parsed)
            if err == nil {
                return save(result)
            } else {
                return err
            }
        } else {
            return err
        }
    } else {
        return err
    }
}

// GOOD: flat, obvious
func process() error {
    data, err := loadData()
    if err != nil {
        return fmt.Errorf("loading: %w", err)
    }
    
    parsed, err := parseData(data)
    if err != nil {
        return fmt.Errorf("parsing: %w", err)
    }
    
    result, err := transform(parsed)
    if err != nil {
        return fmt.Errorf("transforming: %w", err)
    }
    
    return save(result)
}

Naming Consistency

Keep error variable names consistent within a function:

// Use 'err' for the standard error variable
data, err := load()
if err != nil { ... }

result, err := process(data)  // reuse 'err'
if err != nil { ... }

// Use descriptive names when you have multiple errors in scope
loadErr := load()
processErr := process()
if loadErr != nil || processErr != nil { ... }

The “Must” Pattern

For initialisation code where errors are truly unrecoverable:

var templates = template.Must(template.ParseGlob("templates/*.html"))
var config = MustLoadConfig("config.yaml")

func MustLoadConfig(path string) Config {
    cfg, err := LoadConfig(path)
    if err != nil {
        panic(fmt.Sprintf("loading config: %v", err))
    }
    return cfg
}

Use Must functions sparingly. Only for program setup where failure means “can't start.”

What You're Actually Getting

After the initial frustration wears off, here's what explicit errors give you:

Visible failure points. Every line that can fail is marked. No surprises.

Local reasoning. You handle errors where they occur. No tracing back through call stacks.

No performance penalty. Error returns are just values. No stack unwinding, no runtime cost.

Forced consideration. You can't ignore errors accidentally. (Well, you can with _, but it's deliberate.)

Simpler debugging. When something fails, the error message tells you exactly what happened at each level.

The Comparison

Aspect C# Exceptions Go Errors
Syntax try/catch/throw if err != nil
Control flow Non-local jump Normal return
Performance Cost on throw No overhead
Visibility Hidden failure points Explicit everywhere
Ignoring errors Silent (dangerous) Requires explicit _
Stack traces Automatic Manual (or wrap carefully)
Recovery catch blocks Caller decides

The Honest Take

Things I like better than C#:

  • You can see which calls can fail
  • Error handling is local and explicit
  • No surprise exceptions from deep in the stack
  • Errors are values. You can store, compare, wrap them

Things I miss from C#:

  • The happy path being uncluttered
  • Automatic stack traces
  • finally blocks (defer is close but not identical)
  • Not writing the same three lines a thousand times

The verdict:

Go's approach is more verbose but more honest. Once you accept that error handling is part of your code (not something that happens off to the side) the verbosity starts to feel appropriate.

You're not writing boilerplate. You're writing error handling. It just happens to look the same every time because handling errors correctly is repetitive.


Next up: panic and recover. Go's actual exception mechanism, why it exists, and why using it for normal errors will get you judged.