errcapture

package
v1.0.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2022 License: Apache-2.0 Imports: 4 Imported by: 15

Documentation

Overview

Package errcapture implements robust error handling in defer statements using provided return argument.

Close a `io.Closer` interface or execute any function that returns error safely while capturing error. It's often forgotten but it's a caller responsibility to close all implementations of `Closer`, such as *os.File or io.ReaderCloser. Commonly we would use:

defer closer.Close()

This is wrong. Close() usually return important error (e.g for os.File the actual file flush might happen and fail on `Close` method). It's very important to *always* check error. `errcapture` provides utility functions to capture error and add to provided one, still allowing to put them in a convenient `defer` statement:

	func <...>(...) (err error) {
 	...
 	defer errcapture.Do(&err, closer.Close, "log format message")

		...
	}

If Close returns error, `errcapture.Do` will capture it, add to input error if not nil and return by argument.

Example:

	func DoAndClose(f *os.File) (err error) {
		defer errcapture.Do(&err, f.Close, "close file at the end")

		// Do something...
		if err := do(); err != nil {
     	  return err
   	}

		return nil
	}

The errcapture.ExhaustClose function provide the same functionality but takes an io.ReadCloser and exhausts the whole reader before closing. This is useful when trying to use http keep-alive connections because for the same connection to be re-used the whole response body needs to be exhausted.

Check https://pkg.go.dev/github.com/efficientgo/tools/pkg/logerrcapture if you want to just log an error instead.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

func Do(err *error, doer doFunc, format string, a ...interface{})

Do runs function and on error return error by argument including the given error (usually from caller function).

func ExhaustClose

func ExhaustClose(err *error, r io.ReadCloser, format string, a ...interface{})

ExhaustClose closes the io.ReadCloser with error capture but exhausts the reader before.

Types

This section is empty.

Jump to

Keyboard shortcuts

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