package errdefer

import "go.abhg.dev/doc2go/internal/errdefer"

Package errdefer provides functions for running operations that must be deferred until the end of a function, but which may return errors that should be returned from the function.

Index

Examples

Functions

func Close

func Close(err *error, closer io.Closer)

Close calls Close on the given Closer, and joins any error returned with the given error.

Use it inside a defer statement with a named return.

Example

This is a contrived example but to demonstrate errdefer, we need a function that returns an error.

package main

import (
	"io"
	"os"

	"braces.dev/errtrace"
	"go.abhg.dev/doc2go/internal/errdefer"
)

func readFile(name string) (_ []byte, err error) {
	f, err := os.Open(name)
	if err != nil {
		return nil, errtrace.Wrap(err)
	}
	defer errdefer.Close(&err, f)
	// NOTE: err must be a named return.

	return errtrace.Wrap2(io.ReadAll(f))
}

// This is a contrived example
// but to demonstrate errdefer,
// we need a function that returns an error.
func main() {
	_, err := readFile("example_test.go")
	if err != nil {
		panic(err)
	}
}