errs

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2024 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package errs provides an error and validation helpers. It defines a Validator interface for types that can validate themselves and various other error types for aggregating and detailing multiple validation errors.

The Validator interface requires implementing types to provide a Validate method that checks for internal consistency or correctness, returning an error if the validation fails. This allows for self-validating models and other structures, making it easier to ensure data integrity throughout the application.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DIR_EXISTS_ERRNO syscall.Errno = syscall.EEXIST

Functions

func CheckPathError

func CheckPathError(err error, op, path string, innerErr syscall.Errno) bool

CheckPathError is used to deconstruct a pkg/fs.PathError to check its content.

func Must

func Must[T any](ret T, err error) T

Must is a helper that takes a comma-error idiom and returns just the value, panicking if an error occurred.

func New

func New(s string) error

New creates a new error with the given text. It provides a simple way to create errors without needing to use fmt.Errorf or errors.New for basic cases.

func Newf

func Newf(format string, args ...any) error

Newf creates a plain text error from a formatted string (using Error as the backing type). It's a convenient wrapper around fmt.Sprintf, allowing for the creation of formatted error messages without needing fmt.Errorf.

func Wrap

func Wrap(wrapper string, errs ...error) error

Wrap takes a string wrapper and a variadic slice of errors to create a new WrappedError. Any passed errors that are nil are discarded. Returns a WrappedError containing filtered error(s) or nil or no valid errors were passed.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/toolvox/utilgo/pkg/errs"
)

func main() {
	// Creating two errors to wrap
	err1 := errors.New("error 1")
	err2 := errors.New("error 2")

	// Wrapping the errors with additional context
	wrappedErr := errs.Wrap("multiple errors occurred", err1, err2)

	fmt.Println(wrappedErr.Error())

}
Output:

multiple errors occurred: errors: [error 1, error 2]

func Wrapf

func Wrapf(wrapperFormat string, argsAndErrs ...any) error

Wrapf takes a string wrapper and a variadic slice of args and errors to create a new WrappedError. nil errors may be interpreted as additional args. Returns a WrappedError containing filtered error(s) or nil or no valid errors were passed.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/toolvox/utilgo/pkg/errs"
)

func main() {
	// Creating an error to wrap
	err := errors.New("specific error")

	// Wrapping the error with a formatted message
	wrappedErr := errs.Wrapf("failed at %d%%", 50, err)

	fmt.Println(wrappedErr.Error())

}
Output:

failed at 50%: specific error

Types

type Error

type Error string

Error defines a simple string-based error type. It implements the error interface, allowing instances of Error to be used wherever Go errors are expected.

func (Error) Error

func (e Error) Error() string

Error returns the string representation of the error. This method satisfies the error interface for the Error type, making it compatible with Go's built-in error handling.

type Errors

type Errors []error

Errors is a slice of errors intended for easily aggregating errors into a single error.

The default value of Errors or an empty Errors is treated as a nil error.

> nil, default, or empty error elements will be discarded

func (Errors) As

func (e Errors) As(target any) bool

As finds the first error in Errors that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

func (Errors) Clean

func (e Errors) Clean() []error

Clean removes all the zero values (read: nil error or empty error structs).

func (Errors) Error

func (e Errors) Error() string

Error formats the Errors slice into a single string, showing all aggregated errors.

func (Errors) Is

func (e Errors) Is(target error) bool

Is reports whether any error in Errors matches target.

func (Errors) OrNil

func (e Errors) OrNil() error

OrNil checks if the Errors slice is empty and returns nil if true; otherwise, it returns the Errors slice itself as an error.

func (Errors) Unwrap

func (e Errors) Unwrap() []error

Unwrap returns the slice of errors contained within Errors, allowing individual errors to be examined.

func (*Errors) WithError

func (e *Errors) WithError(err error)

WithError appends a new error to the Errors slice.

If the error is nil, nothing is appended.

func (*Errors) WithErrorf

func (e *Errors) WithErrorf(format string, args ...interface{})

WithErrorf appends a new error, formatted according to a format specifier, to the Errors slice.

"%w" is supported as this is a wrapper for fmt.Errorf.

type Validator

type Validator interface {
	// Validate checks the object for validity, returning an error if it is not valid.
	// The error returned can be cast to a Errors type to inspect individual errors.
	Validate() error
}

Validator is an interface implemented by types capable of self-validation. The Validate method is intended to check the implementing type for internal consistency or correctness, returning an error if validation fails.

Implementors of Validator should return nil if the object is considered valid, or any error if there are specific validation errors to report.

You're free to return any error type, Errors is provided as a convenience.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/toolvox/utilgo/pkg/errs"
)

// ExampleType shows how a type can implement the Validator interface.
type ExampleType struct {
	Field1 string
	Field2 int
}

// Validate implements the Validator interface for ExampleType.
// It checks multiple conditions and aggregates any errors found using Errorf.
func (et ExampleType) Validate() error {
	var errors errs.Errors

	if strings.TrimSpace(et.Field1) == "" {
		errors.WithErrorf("Field1 must not be empty")
	}

	if et.Field2 <= 0 {
		errors.WithErrorf("Field2 must be positive")
	}

	// an accidental nil
	errors = append(errors, nil)

	if len(errors.Unwrap()) > 0 {
		errors.WithErrorf("%s error: %w", "another", errs.New("inner error"))
	}

	return errs.Wrap("validation", errors.OrNil())
}

func main() {
	exampleInvalid := ExampleType{Field1: "", Field2: -1}
	fmt.Printf("Validating: %#v\n", exampleInvalid)

	if err := exampleInvalid.Validate(); err != nil {
		fmt.Println("Validation failed:\n", err)
	} else {
		fmt.Println("Validation passed")
	}

	exampleValid := ExampleType{Field1: "Bob", Field2: 13}
	fmt.Printf("Validating: %+v\n", exampleValid)

	if err := exampleValid.Validate(); err != nil {
		fmt.Println("Validation failed:\n", err)
	} else {
		fmt.Println("Validation passed")
	}

}
Output:

Validating: errs_test.ExampleType{Field1:"", Field2:-1}
Validation failed:
 validation: errors: [Field1 must not be empty, Field2 must be positive, another error: inner error]
Validating: {Field1:Bob Field2:13}
Validation passed

type WrappedError

type WrappedError struct {
	Message string
	Wrapped error
}

WrappedError represents an error that wraps another error with an additional message. It allows for adding context to the original error, making it easier to understand the error's origin and nature.

func (WrappedError) As

func (e WrappedError) As(target any) bool

As finds the first error in WrappedError's tree that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/toolvox/utilgo/pkg/errs"
)

func main() {
	// Creating a custom error type
	customErr := errs.Error("custom error")

	// Wrapping the custom error
	wrappedErr := errs.Wrap("context", customErr)

	// Attempting to type-assert the wrapped error back to the custom type
	var targetErr errs.Error
	if errors.As(wrappedErr, &targetErr) {
		fmt.Println(targetErr)
	} else {
		fmt.Println("error does not match")
	}

}
Output:

custom error

func (WrappedError) Error

func (e WrappedError) Error() string

Error returns a formatted string combining the message and the wrapped error. The format is "<Message>: <Wrapped Error>", providing a clear indication of the context followed by the original error.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/toolvox/utilgo/pkg/errs"
)

func main() {
	// Creating a base error
	baseErr := errors.New("this is a base error")

	// Wrapping the base error with additional context
	wrappedErr := errs.WrappedError{
		Message: "failed due to external system",
		Wrapped: baseErr,
	}

	// Printing the error
	fmt.Println(wrappedErr.Error())

}
Output:

failed due to external system: this is a base error

func (WrappedError) Is

func (e WrappedError) Is(target error) bool

Is reports whether any error in WrappedError's tree matches target.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/toolvox/utilgo/pkg/errs"
)

func main() {
	// Creating a target error to check against
	targetErr := errors.New("target error")

	// Creating a wrapped error containing the target error
	wrappedErr := errs.Wrap("additional context", targetErr)

	// Checking if the wrapped error contains the target error
	fmt.Println(errors.Is(wrappedErr, targetErr))

}
Output:

true

func (WrappedError) Unwrap

func (e WrappedError) Unwrap() error

Unwrap returns the original error that was wrapped. This allows errors.Is and errors.As to work with WrappedError, facilitating error inspection and handling.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/toolvox/utilgo/pkg/errs"
)

func main() {
	// Creating a base error and wrapping it
	baseErr := errors.New("base error")
	wrappedErr := errs.Wrap("context added", baseErr)

	// Unwrapping the error
	unwrappedErr := errors.Unwrap(wrappedErr)
	fmt.Println(unwrappedErr)

}
Output:

base error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL