iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🥅

Properly Handling Errors in Defer Statements with Goalie

に公開
2025/09/02

This article is a supplementary material for the LT "Never miss defer'd errors!" presented at golang.tokyo #40.
See the slides at talks.ras0q.com.

https://x.com/ras0q/status/1962463413508202897

Common defer statement troubles

When developing applications or tools in Go, hasn't everyone at some point struggled with error handling in defer statements?
Since some of you may not be familiar with the issue yet, let me introduce a simple example. If you have used defer statements, I think you'll quickly understand.


The following code is a function (processFile) that opens a file from the given file path and performs some processing.
The opened file resource must be properly closed when the function ends. Properly closing the file prevents it from being continuously occupied by the system unnecessarily.

func processFile(path string) error {
    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer f.Close() // ⚠️
    // ... Do something ...

    return nil
}

Here, the function f.Close() that closes the file returns an error, but we are only executing it without writing any code to receive that error.

If you have errcheck enabled in your project via linters like govet or golangci-lint, you will receive the following error.
Many people have suffered from this error, haven't they?

errcheck: Error return value of `f.Close` is not checked


As a countermeasure against the errcheck warning, we often see patterns like the following, where the return error of f.Close() is used and logged.

func processFile(path string) error {
    f, err := os.Open(path)
    if err != nil {
        return err
    }
-   defer f.Close() // ⚠️
+   defer func() {
+       if cerr := f.Close(); cerr != nil {
+           log.Printf("failed to close: %v", cerr)
+       }
+   }()
    // ... do something ...

    return nil
}

Compared to the previous case where errors were completely ignored, logging errors makes it easier for developers to discover them.
However, the error from f.Close() is not propagated to the function processFile itself, so this function will terminate normally even though an error actually occurred.


The operations executed in defer statements are not limited to closing files. defer is used in various places, such as closing database connections or closing HTTP client response bodies.
And every time you ignore the return error, you get the same warning from errcheck.


And you, the developer, get tired of this warning and eventually write a control comment to ignore all warnings...

func processFile(path string) error {
    f, err := os.Open(path)
    if err != nil {
        return err
    }
-   defer f.Close() // ⚠️
+   defer f.Close() //nolint: errcheck

    // ... Do something ...

    return nil
}

Once this happens, not only you but also other developers will be completely unaware of errors occurring in defer statements.

What should have been done then?

So, how should we have actually handled this?

To solve this problem with defer statements, I developed a library called "Goalie".


Goalie?

Goalie (ras0q/goalie) is a library specialized in error handling for functions executed in defer statements.
It has only one feature: it collects errors from functions like f.Close() executed in defer statements and returns them all together at the caller (in the previous example, processFile).

https://github.com/ras0q/goalie

By the way, the name "Goalie" is taken from an alternative name for a goalkeeper.
Semantically, it also starts with "Go", which is perfect, and I really like it.

In many team sports that involve scoring goals, the goalkeeper (sometimes termed goaltender, netminder, GK, goalie, or keeper) is a designated player charged with directly preventing the opposing team from scoring by blocking or intercepting opposing shots on goal.
https://en.wikipedia.org/wiki/Goalkeeper


Using Goalie, you can handle defer errors as follows:

-func processFile(path string) error {
+func processFile(path string) (err error) {
+   g := goalie.New()
+   defer g.Collect(&err) // ✅ Collect errors...

    f, err := os.Open(path)
    if err != nil {
        return err
    }
-   defer f.Close()
+   defer g.Guard(f.Close) // ✅ Guarded!

    // ... do something ...

    return nil
}

Change the return value to a named return value and define the variable err at the beginning of the function.
This allows you to modify the error returned to the caller after the return statement.

Once the named return value is set, create a Goalie instance and use g.Collect(&err) to associate with the error err you just defined and collect subsequent errors.
Since errors need to be collected last and returned to the caller, execute it with defer.
By the way, since g.Collect has no return value, this line will not be warned by errcheck.

+   g := goalie.New()
+   defer g.Collect(&err) // ✅ Collect errors...

Next, wrap the part where you previously closed the file with Goalie. This way, even if an error occurs during closure, it will be collected by the previously set defer g.Collect(&err).

-   defer f.Close()
+   defer g.Guard(f.Close) // ✅ Guarded!
Goalie Demo

Add a file writing process writeToFile to the processFile we have been using.
However, writeToFile has a bug: it closes the file passed as an argument inside this function. This means the file will be closed twice, once in writeToFile and once in processFile, so the second f.Close() in processFile should produce an error.

In this demo, we verify that this bug is correctly detected and the function terminates abnormally (words are hard).

// Function that opens a given path and writes a string
func processFile(path string) (err error) {
    g := goalie.New()
    defer g.Collect(&err)

    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer g.Guard(f.Close)

    // File write
    writeToFile(f)

    // Assuming an error also occurred in another process
    return ErrInternal
}

var ErrInternal = errors.New("internal error")

// Function to write a string to a file
// 🚨 Closing the passed file inside this function
func writeToFile(f *os.File) {
    f.Write([]byte("Hello, golang.tokyo!"))
    f.Close()
}

Call processFile from the main function and run it; you can see that it correctly detects the error as an error.

func main() {
    err := processFile("input.txt")
    if err != nil {
        fmt.Printf("[ERROR]:\n%+v\n\n", err)
        fmt.Println(
            "is os.ErrClosed?:",
            errors.Is(err, os.ErrClosed),
        )
        fmt.Println(
            "is ErrInternal?: ",
            errors.Is(err, ErrInternal),
        )
    }
}
$ go run main.go
[ERROR]:
internal error
close go.mod: file already closed

is os.ErrClosed?: true
is ErrInternal?:  true

Implementation Explanation

In fact, the core part of Goalie's implementation consists of just these 14 lines.
It's a simple implementation that stacks errors with Guard and combines them into a single error with Collect.

type Goalie struct {
    errs []error
}

func (g *Goalie) Guard(errFunc func() error) {
    if err := errFunc(); err != nil {
        g.errs = append([]error{err}, g.errs...)
    }
}

func (g *Goalie) Collect(errp *error) {
    errs := append(g.errs, *errp)
    *errp = errors.Join(errs...)
}

This idea is based on error handling techniques used officially by Go.
In golang.org/x/pkgsite, which composes Go Packages, wrapping the named return value err with defer is frequently used as follows:

func Wrap(errp *error, format string, args ...any) {
    if *errp != nil {
        *errp = fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), *errp)
    }
}

// NewServer creates a new Server for the given database and template directory.
func NewServer(scfg ServerConfig) (_ *Server, err error) {
    defer derrors.Wrap(&err, "NewServer(...)")

    s := &Server{ ... }

    return s, nil
}

The following article summarizes this well, so please check it out if you're interested.

pkgsite/internal/derrors を使ったGoのエラーラッピング

https://zenn.dev/furon/articles/b7275043eb7dcb


The core implementation is 14 lines, but we also provide options to use it with other error handling libraries.
Below is an example integrating with cockroachdb/errors.

import (
    "github.com/cockroachdb/errors"
    "github.com/ras0q/goalie"
)

func processFile(path string) (err error) {
    g := goalie.New(
        goalie.WithJoinErrorsFunc(errors.Join),
    )
    defer g.Collect(&err)

    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer g.Guard(f.Close)

    // ... Do something ...

    return nil
}

Use Goalie Now

After all, since I ended up writing //nolint due to being exhausted by the countless errcheck warnings, even with Goalie developed, it's still cumbersome to add it to every single spot one by one.

Don't worry. We have prepared a migration tool.
Run the following command on your existing project to verify Goalie is integrated.

go run github.com/ras0q/goalie/usegoalie/cmd/usegoalie@latest -fix ./...

As a side note, the migration tool relies heavily on LLM. Offloading convenient features that are not essential to the library itself (where bugs would not be critical) to an LLM was a good experience.
Also, providing a migration tool for the library you want people to use in the form of a CLI like use{foo} is a short and precise way to convey intent, so I'm quite fond of it.

Conclusion

Thank you for your attention.
(And thank you to those who read the article this far.)

Please consider incorporating Goalie into your Go projects.
If you like it, I would be very happy if you could star it on GitHub.

Discussion