Capture Close Errors With Named Returns

A named result lets a deferred function rewrite the error after return: the Close failure is never lost and only wins when the body had none.

GoData Integrity

Code

gosnippet
35 lines
package main

import (
	"fmt"
	"os"
)

// saveFile 用命名返回值 (err error):defer 里可以在 return 之后继续补写 err
func saveFile(name string, payload []byte) (err error) {
	f, err := os.Create(name)
	if err != nil {
		return err
	}
	defer func() {
		if cerr := f.Close(); cerr != nil && err == nil {
			// Close 的错误不能丢:仅当主流程没有错误时才覆盖
			err = cerr
		}
	}()
	_, err = f.Write(payload)
	return err
}

func main() {
	if err := saveFile("report.txt", []byte("quarterly data\n")); err != nil {
		fmt.Println("save failed:", err)
		return
	}
	data, err := os.ReadFile("report.txt")
	if err != nil {
		panic(err)
	}
	fmt.Printf("saved %d bytes: %s", len(data), data)
	os.Remove("report.txt")
}

What runs when

Every runnable line is contained in the functions saveFile and main.

The Go idiom runs throughout — 4 if err != nil checks, each handling the failure on the spot. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

What to watch for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.
  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Applying it

The method shape you reuse: func saveFile(name string, payload []byte) (err error)

The demo output is labeled (save failed:, saved), so the printed output reads as a trace of the operations performed.

The entry point wires saveFile together — run it once and the whole demo flows.

Statements that matter

if err != nil {
return err
}
if err != nil {
panic(err)
}
defer func() {
if cerr := f.Close(); cerr != nil && err == nil {
// Close 的错误不能丢:仅当主流程没有错误时才覆盖
err = cerr
}
}()

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
Through `error` values — the snippet checks `err != nil` at 4 sites, and the entry flow turns failures into `panic(err)`.
What does Capture Close Errors With Named Returns print when run?
Run it as a complete program — the output lines carry labels such as `save failed:`, `saved`.