Learn Go · 8/18

Error Handling: Building Robust Applications

8 min read

Error Handling: Building Robust Applications

Welcome, Go developers! 👋 Let's talk about something that isn't always the most glamorous part of coding but is absolutely critical for building applications that don't fall over when a stiff breeze blows: error handling. In Go, handling errors is a core part of the language's philosophy, and it encourages you to be explicit and thoughtful about what could go wrong.

1. The error Interface: Go's Approach to Failures 🧐

The Problem: In many programming languages, errors are handled with exceptions. You try a block of code, and if something goes wrong, it's caught elsewhere. This can sometimes feel like playing a game of hot potato with your errors – you're never quite sure who's going to catch it. This can lead to what's called "hidden control flow," where it's not obvious from reading the code that an error might interrupt the normal execution.

The Go Solution: Go takes a different path. Instead of exceptions, functions that can fail return an error value alongside their normal result. This makes the possibility of an error explicit and encourages you to deal with it right where it happens.

At its heart, Go's error handling is built on a very simple concept: the error interface. It's so simple, it only has one method:

go
type error interface {
    Error() string
}

Any type that implements this Error() method is considered an error. This means you can create your own custom error types, which we'll get to shortly.

The most common way to create a simple error is by using the errors.New function from the standard errors package.

Example: A Classic if err != nil

Let's imagine you're trying to open a file. This is a classic operation that can fail for many reasons (the file doesn't exist, you don't have permission, etc.).

go
package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("a_file_that_does_not_exist.txt")
    if err != nil {
        fmt.Println("Oh no, something went wrong:", err)
        return
    }
    // If we get here, the file was opened successfully!
    fmt.Println("File opened successfully:", file.Name())
}

In this example, os.Open can return a file and an error. The idiomatic Go way to handle this is to immediately check if the err is not nil. If it's not, we know something went wrong, and we can handle it (in this case, by printing a message and stopping).

This pattern of if err != nil is something you'll see everywhere in Go code. While it might seem a bit repetitive at first, it makes the code very clear and easy to follow. You always know when a function might fail and are forced to consider what to do in that case.

2. Creating and Wrapping Custom Errors 🎁

The Problem: Sometimes, a simple error string like "something went wrong" just isn't enough. You might need to provide more context, like an error code, or distinguish between different kinds of failures.

The Solution: Since error is an interface, you can create your own custom error types. This is as simple as defining a struct and implementing the Error() method.

Example: A Custom Error Type

Let's say we're building a system that processes payments and we want a specific error for when there are insufficient funds.

go
package main

import (
    "fmt"
)

// Our custom error type
type InsufficientFundsError struct {
    Amount  float64
    Balance float64
}

// Implement the Error() method
func (e *InsufficientFundsError) Error() string {
    return fmt.Sprintf("cannot withdraw %.2f, balance is only %.2f", e.Amount, e.Balance)
}

func Withdraw(amount float64, balance float64) error {
    if amount > balance {
        return &InsufficientFundsError{Amount: amount, Balance: balance}
    }
    // Process withdrawal
    fmt.Println("Withdrawal successful")
    return nil
}

func main() {
    err := Withdraw(100.0, 50.0)
    if err != nil {
        fmt.Println("Error:", err)
    }
}

Now, our Withdraw function returns a much more informative error.

Error Wrapping: Adding Context to Errors

Another powerful feature introduced in Go 1.13 is error wrapping. This allows you to add context to an error while preserving the original error. This is incredibly useful for debugging, as it allows you to trace an error back through the layers of your application.

To wrap an error, you use the %w verb in fmt.Errorf.

Example: Wrapping an Error

go
package main

import (
    "errors"
    "fmt"
    "os"
)

func readFile() error {
    _, err := os.Open("non_existent_file.txt")
    if err != nil {
        return fmt.Errorf("failed to read file: %w", err)
    }
    return nil
}

func main() {
    err := readFile()
    if err != nil {
        fmt.Println(err)
        // We can still get the original error!
        originalErr := errors.Unwrap(err)
        fmt.Println("Original error:", originalErr)
    }
}

Here, readFile adds context to the error from os.Open. We can then use errors.Unwrap to get the original, underlying error.

A more common way to inspect wrapped errors is with errors.Is and errors.As.

  • errors.Is: Checks if any error in the chain matches a specific error value.
  • errors.As: Checks if any error in the chain matches a specific type and, if so, assigns it to a variable.

Example: Using errors.Is and errors.As

go
package main

import (
    "errors"
    "fmt"
    "os"
)

type MyCustomError struct {
    msg string
}

func (e *MyCustomError) Error() string {
    return e.msg
}

func doSomething() error {
    return fmt.Errorf("an error occurred: %w", &MyCustomError{"this is my custom error"})
}

func main() {
    err := doSomething()

    var customErr *MyCustomError
    if errors.As(err, &customErr) {
        fmt.Println("This is a MyCustomError:", customErr)
    }

    if errors.Is(err, os.ErrNotExist) { // This will be false in this case
        fmt.Println("The file does not exist.")
    }
}

3. The defer Keyword: Cleaning Up Resources 🧹

The Problem: When you open a file, establish a network connection, or acquire a lock, you need to make sure you release those resources when you're done. Forgetting to do so can lead to resource leaks and other nasty bugs. It can be easy to forget a cleanup step, especially if a function has multiple return paths.

The Solution: Go's defer keyword provides a simple and elegant way to ensure that a function call is executed just before the surrounding function returns, no matter how it returns (either through a return statement or a panic).

Example: Using defer to Close a File

go
package main

import (
    "fmt"
    "os"
)

func readFile(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close() // This will be called when readFile returns

    // ... do something with the file ...
    fmt.Println("File opened successfully")
    return nil
}

func main() {
    readFile("some_file.txt")
}

By deferring file.Close(), we guarantee that the file will be closed when readFile finishes, even if an error occurs later in the function.

Interesting Fact: If you have multiple defer statements in a function, they are executed in a Last-In, First-Out (LIFO) order. Think of it like a stack of plates: the last one you put on is the first one you take off.

Example: Multiple defers

go
package main

import "fmt"

func main() {
    defer fmt.Println("First")
    defer fmt.Println("Second")
    fmt.Println("Third")
}

// Output:
// Third
// Second
// First

4. Panic and Recover: Handling the Unexpected 🚨

The Problem: Sometimes, a truly unexpected and unrecoverable error occurs. This could be a bug in your code, like trying to access an index that's out of bounds in an array. In these situations, the program can't continue safely.

The Go Solution: Go has a mechanism for dealing with these exceptional circumstances: panic and recover.

  • panic: A built-in function that stops the ordinary flow of control and begins "panicking." It's generally used for unrecoverable errors. When a function panics, its execution stops, any deferred functions are executed, and then it returns to its caller. This process continues up the stack until the program crashes.

  • recover: A built-in function that can regain control of a panicking goroutine. recover is only useful inside deferred functions. If the current goroutine is panicking, a call to recover will capture the value passed to panic and resume normal execution.

When to Use panic:

In idiomatic Go, you should avoid using panic for normal error handling. A good rule of thumb is to use panic only when the program cannot continue execution in a sensible way. For example, if a web server can't bind to its required port, it can't serve requests, so it's reasonable for it to panic.

Example: A Simple panic

go
package main

import "fmt"

func main() {
    fmt.Println("start")
    panic("something went terribly wrong")
    fmt.Println("end") // This will not be executed
}

Example: Using recover

You can use recover to prevent a panic from crashing the entire program. This is often used in web servers to ensure that a single panicking request doesn't bring down the whole server.

go
package main

import "fmt"

func handleRequest() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    
    // Simulate a panic
    panic("a problem in the request handler")
}

func main() {
    handleRequest()
    fmt.Println("Program continues to run")
}

Funny Exaggeration: Think of panic as flipping the table in a board game. You should only do it when the game has gone so wrong that there's no other option. And recover is like your friend who calmly starts picking up the pieces so you can try again later.


Further Reading 📚

Challenge

You are tasked with building a robust transaction processing system in Go that correctly handles various failure scenarios using idiomatic error handling patterns.

Your tasks:

  1. Define a Custom Error:
    Create a struct named InsufficientFundsError that contains one field: shortfall of type float64. Implement the error interface for this struct. The Error() method should return a string formatted as: cannot withdraw, shortfall of %.2f.

  2. Implement the Core Logic:
    Create a function withdraw(balance float64, amount float64) (float64, error).

    • If amount is greater than balance, it must return 0 and an instance of InsufficientFundsError with the calculated shortfall (amount - balance).
    • If amount is negative, it must panic with the string message "withdrawal amount cannot be negative".
    • On success, it should return the new balance (balance - amount) and a nil error.
  3. Create a Robust Wrapper:
    Create a function processWithdrawal(accountID string, balance float64, amount float64) (finalBalance float64, err error).

    • This function must use defer and recover to gracefully handle any panic from the withdraw function. If a panic is recovered, processWithdrawal should return 0 and a new error created with fmt.Errorf, wrapping the recovered panic value, like so: internal system failure: %v.
    • If the withdraw function returns an error, processWithdrawal must wrap that error with additional context using fmt.Errorf and the %w verb. The new error message should be: transaction for account %s failed: %w.
  4. Handle Errors in main:
    In the main function provided in the initial code, complete the section marked with a TODO. You must use errors.As to check if the error returned from the second processWithdrawal call is of type *InsufficientFundsError.

    • If it is, print the specific error message from your custom error type in a new line, formatted as: Specific error: %v.

Expected result

Your implementation should produce output that correctly handles all three scenarios described in the main function.

  • Scenario 1 should print a success message with the new balance of 20.00.
  • Scenario 2 should first print the full, wrapped error message: Top-level error: transaction for account acc_102 failed: cannot withdraw, shortfall of 70.00. Then, because your errors.As check should succeed, it should print the specific, unwrapped error message on a new line: Specific error: cannot withdraw, shortfall of 70.00.
  • Scenario 3 should print the error created from the recovered panic: Recovered from panic, error: internal system failure: withdrawal amount cannot be negative.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.