Documentation
¶
Overview ¶
Package warning provides a simple way to handle errors that should not stop execution (return err), but rather continue.
Common Go idiom is this:
if err != nil {
return err
}
But what if you wanted to distinguish between error that ends execution and error that should just be logged? This package provides you with just that.
if err != nil && warning.IsWarning(err) {
// This is executed only if err is not a warning.
return
}
It also works well with https://github.com/pkg/errors and https://github.com/hashicorp/go-multierror.
Example ¶
package main
import (
"fmt"
"warning"
"github.com/hashicorp/go-multierror"
)
func main() {
myfunc := func() error {
// Suppose more complicated function here.
var multierr *multierror.Error
for i := 0; i <= 10; i++ {
// Process data but do not stop on errors, create just warnings.
msg := fmt.Sprintf("Item %d did not complete.", i)
multierr = multierror.Append(multierr, warning.New(msg))
}
return multierr.ErrorOrNil()
}
err := myfunc()
if err != nil && !warning.IsWarning(err) {
// Stop execution if error is not a warning.
return
}
fmt.Println(err)
}
Output: 11 errors occurred: * Item 0 did not complete. * Item 1 did not complete. * Item 2 did not complete. * Item 3 did not complete. * Item 4 did not complete. * Item 5 did not complete. * Item 6 did not complete. * Item 7 did not complete. * Item 8 did not complete. * Item 9 did not complete. * Item 10 did not complete.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Wrap ¶
Wrap wraps any error into Warning.
Example ¶
package main
import (
"errors"
"fmt"
"warning"
)
func main() {
err := warning.Wrap(errors.New("something happened but I don't want to stop"))
if err != nil && warning.IsWarning(err) {
fmt.Println("this is a warning")
}
}
Output: this is a warning
Types ¶
type Warning ¶
type Warning struct {
// contains filtered or unexported fields
}
Warning type wraps error interface. This type is used to represent error that should not cause stopping of execution, but just be logged and continue.
func (*Warning) Cause ¶
Cause returns the underlying cause of Warning.
Example ¶
package main
import (
"fmt"
"warning"
"github.com/hashicorp/go-multierror"
)
func main() {
myfunc := func() error {
// Suppose more complicated function here.
var multierr *multierror.Error
for i := 0; i <= 10; i++ {
// Process data but do not stop on errors, create just warnings.
err := fmt.Errorf("Item %d did not complete.", i)
multierr = multierror.Append(multierr, err)
}
return warning.Wrap(multierr.ErrorOrNil())
}
// Access the underlying cause.
err := myfunc()
switch e := err.(type) {
case warning.Warning:
// Now you can access multierror's WrappedErrors()
fmt.Printf("%T", e.Cause())
}
}
Output: *multierror.Error
Click to show internal directories.
Click to hide internal directories.