Documentation
¶
Overview ¶
Package errorx provides small helpers for common error handling patterns.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FirstErr ¶ added in v1.2.0
FirstErr returns the first non-nil error from the provided errors, or nil if all errors are nil. It is useful for reducing a set of validation or initialization errors to a single result without chaining multiple if statements.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/SharkByteSoftware/go-snk/errorx"
)
func main() {
validate := func(name string, age int) error {
return errorx.FirstErr(
validateName(name),
validateAge(age),
)
}
fmt.Println(validate("alice", 30))
fmt.Println(validate("", 30))
}
func validateName(name string) error {
if name == "" {
return errors.New("name is required")
}
return nil
}
func validateAge(age int) error {
if age < 0 {
return errors.New("age must be non-negative")
}
return nil
}
Output: <nil> name is required
Example (AllNil) ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/errorx"
)
func main() {
err := errorx.FirstErr(nil, nil, nil)
fmt.Println(err)
}
Output: <nil>
func Ignore ¶
func Ignore(_ error)
Ignore explicitly discards an error. It is intended to document intentional error suppression rather than silently assigning to _.
Example ¶
package main
import (
"fmt"
"os"
"github.com/SharkByteSoftware/go-snk/errorx"
)
func main() {
// Use Ignore to explicitly document that an error is intentionally discarded.
errorx.Ignore(os.Remove("file-that-may-not-exist.tmp"))
fmt.Println("done")
}
Output: done
func IsAny ¶
IsAny reports whether err matches any of the provided targets, using errors.Is semantics for each comparison.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/SharkByteSoftware/go-snk/errorx"
)
func main() {
var (
errNotFound = errors.New("not found")
errForbidden = errors.New("forbidden")
errBadRequest = errors.New("bad request")
)
err := fmt.Errorf("request failed: %w", errForbidden)
if errorx.IsAny(err, errNotFound, errForbidden) {
fmt.Println("client error")
}
fmt.Println(errorx.IsAny(err, errBadRequest))
}
Output: client error false
func Must ¶
Must return the value if err is nil, and panics otherwise. It is intended for use at program initialization time when an error represents a non-recoverable misconfiguration.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/SharkByteSoftware/go-snk/errorx"
)
func main() {
parse := func(s string) (int, error) {
if s == "" {
return 0, errors.New("empty input")
}
return len(s), nil
}
result := errorx.Must(parse("hello"))
fmt.Println(result)
}
Output: 5
Types ¶
This section is empty.