Documentation
¶
Overview ¶
Package grouperror provides a toolset to join and split errors.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/gontainer/grouperror"
)
func main() {
err := grouperror.Prefix("my group: ", errors.New("error1"), nil, errors.New("error2"))
for _, x := range grouperror.Collection(err) {
fmt.Println(x)
}
}
Output: my group: error1 my group: error2
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Collection ¶
Collection extracts an error collection from the given error if it has a `Collection() []error` method. It works recursively.
err := grouperror.Prefix("my group: ", errors.New("error1"), nil, errors.New("error2"))
for _, x := range grouperror.Collection(err) {
fmt.Println(x)
}
// Output:
// my group: error1
// my group: error2
func Join ¶
Join joins provided errors. It ignores nil-values. It returns nil, when there are no errors given.
func Prefix ¶
Prefix joins errors the same way as Join, and adds a prefix to the group.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/gontainer/grouperror"
)
func main() {
err := grouperror.Prefix(
"validation: ",
errors.New("invalid name"),
nil, // nil-errors are being ignored
nil,
errors.New("invalid age"),
)
err = grouperror.Prefix(
"could not create new user: ",
errors.New("unexpected error"),
err,
)
err = grouperror.Prefix("operation failed: ", err)
fmt.Println(err.Error())
fmt.Println()
for i, x := range grouperror.Collection(err) {
fmt.Printf("%d. %s\n", i+1, x.Error())
}
}
Output: operation failed: could not create new user: unexpected error operation failed: could not create new user: validation: invalid name operation failed: could not create new user: validation: invalid age 1. operation failed: could not create new user: unexpected error 2. operation failed: could not create new user: validation: invalid name 3. operation failed: could not create new user: validation: invalid age
Example (Stdlib) ¶
package main
import (
"errors"
"fmt"
)
func main() {
// [errors.Join] has been introduced in go 1.20
// https://tip.golang.org/doc/go1.20#errors
err := errors.Join(
errors.New("invalid name"),
nil,
nil,
errors.New("invalid age"),
)
err = fmt.Errorf("validation: %w", err)
err = errors.Join(
errors.New("unexpected error"),
err,
)
err = fmt.Errorf("could not create new user: %w", err)
err = fmt.Errorf("operation failed: %w", err)
fmt.Println(err.Error())
}
Output: operation failed: could not create new user: unexpected error validation: invalid name invalid age
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.