errdefer

package
v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2024 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

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

Constants

This section is empty.

Variables

This section is empty.

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)
	}
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL