Documentation
¶
Overview ¶
Package errbatch is DEPRECATED. Please use https://pkg.go.dev/github.com/reddit/baseplate.go/batcherror instead.
Package errbatch provides ErrBatch, which can be used to compile multiple errors into a single error.
An example of how to use it in your functions:
type worker func() error
func runWorksParallel(works []worker) error {
errChan := make(chan error, len(works))
var wg sync.WaitGroup
wg.Add(len(works))
for _, work := range works {
go func(work worker) {
errChan <- work()
}(work)
}
wg.Wait()
var batch errbatch.ErrBatch
for err := range errChan {
// nil errors will be auto skipped
batch.Add(err)
}
// If all works succeeded, Compile() returns nil.
// If only one work failed, Compile() returns that error directly
// instead of wrapping it inside ErrBatch.
return batch.Compile()
}
This package is not thread-safe. The same batch should not be operated on different goroutines.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/fishy/errbatch"
)
func main() {
var batch errbatch.ErrBatch
var singleError error = batch.Compile()
fmt.Printf("0: %v\n", singleError)
err := errors.New("foo")
batch.Add(err)
singleError = batch.Compile()
fmt.Printf("1: %v\n", singleError)
batch.Add(nil)
singleError = batch.Compile()
fmt.Printf("Nil errors are skipped: %v\n", singleError)
err = errors.New("bar")
batch.Add(err)
singleError = batch.Compile()
fmt.Printf("2: %v\n", singleError)
var newBatch errbatch.ErrBatch
err = errors.New("foobar")
newBatch.Add(err)
newBatch.Add(batch)
fmt.Printf("3: %v\n", newBatch.Compile())
}
Output: 0: <nil> 1: foo Nil errors are skipped: foo 2: errbatch: total 2 error(s) in this batch: foo; bar 3: errbatch: total 3 error(s) in this batch: foobar; foo; bar
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ErrBatch ¶
type ErrBatch struct {
// contains filtered or unexported fields
}
ErrBatch is an error that can contain multiple errors.
The zero value of ErrBatch is valid (with no errors) and ready to use.
func (*ErrBatch) Add ¶
Add adds an error into the batch.
If the error is also an ErrBatch, its underlying error(s) will be added instead of the ErrBatch itself.
Nil error will be skipped.
func (*ErrBatch) Compile ¶
Compile compiles the batch.
If the batch contains zero errors, it will return nil.
If the batch contains exactly one error, that underlying error will be returned.
Otherwise, the batch itself will be returned.