Documentation
¶
Overview ¶
Package errors provides utilities for creating, wrapping, combining, and inspecting errors.
It is 100% dependency-free and works perfectly with the standard library's errors package (Go 1.20+). Multi-errors support errors.Is, errors.As, and errors.Unwrap out of the box.
Index ¶
- func Append(err error, errs ...error) error
- func As(err error, target any) bool
- func Errorf(format string, args ...any) error
- func Errors(err error) []error
- func Flatten(err error) error
- func Is(err, target error) bool
- func Join(errs ...error) error
- func New(msg string) error
- func Prefix(err error, prefix string) error
- func Unwrap(err error) error
- func WithMessage(err error, msg string) error
- func Wrap(err error, msg string) error
- func Wrapf(err error, format string, args ...any) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Append ¶
Append combines multiple errors into a multi-error. Returns nil if all errors are nil.
func Errors ¶
Errors returns the list of underlying errors. If err is not a multi-error, returns a single-element slice.
Example ¶
package main
import (
"fmt"
"github.com/jwm1rr0rb10/go-errors"
)
func main() {
err := errors.Append(
errors.New("validation failed"),
errors.New("user already exists"),
)
for _, e := range errors.Errors(err) {
fmt.Println(e)
}
}
Output: validation failed user already exists
func Flatten ¶
Flatten returns a single error if the multi-error contains only one error. Otherwise returns the multi-error unchanged.
func Prefix ¶
Prefix adds the same prefix to every error inside err (works for both single errors and multi-errors).
Example ¶
package main
import (
"fmt"
"github.com/jwm1rr0rb10/go-errors"
)
func main() {
err1 := errors.New("permission denied")
err2 := errors.New("disk full")
err := errors.Append(err1, err2)
err = errors.Prefix(err, "backup failed")
fmt.Println(err)
}
Output: 2 errors occurred: - backup failed: permission denied - backup failed: disk full
func WithMessage ¶
WithMessage adds msg as a sibling error. If err is nil, returns a plain error with msg.
func Wrapf ¶
Wrapf wraps err with a formatted message. If err is nil, returns nil.
Example ¶
package main
import (
"fmt"
"github.com/jwm1rr0rb10/go-errors"
)
func main() {
err := errors.New("connection refused")
err = errors.Wrapf(err, "failed to dial %s:%d", "db.example.com", 5432)
fmt.Println(err)
}
Output: failed to dial db.example.com:5432: connection refused
Types ¶
This section is empty.