try

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2023 License: MIT Imports: 2 Imported by: 6

README

try

Package try simplifies the error handling in waiting Go 2 error handling.

It is not the perfect solution, and it is not recommended to use in the libraries, but it can help for the simple apps.

See the package documentation for details.

Documentation

Overview

Package try simplifies the error handling in waiting Go 2 error handling.

It is not the perfect solution, and it is not recommended to use in the libraries, but it can help for the simple apps.

In Go it is common to handle errors like this:

func foo() error {
  v, err := bar()
  if err != nil {
    return err
  }

  if err := bar2(v); err != nil {
    return err
  }

  return nil
}

It gets tedious when there are a lot of these checks. With the try package you can replace this code to:

func foo() (outErr error) {
  defer try.HandleAs(*outErr)

  v := try.ItVal(bar())

  try.It(bar2(v))

  return nil
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Func added in v0.1.4

func Func(fn func()) func() error

Func takes a function that can throw try.* error and returns a function that returns this error in a regular Go style.

func FuncArg added in v0.1.4

func FuncArg[T any](fn func(x T)) func(x T) error

FuncArg takes a function with one argument that can throw try.* error and returns a function that returns this error in a regular Go style.

func FuncArgOut added in v0.1.4

func FuncArgOut[T any, U any](fn func(x T) U) func(x T) (U, error)

FuncArgOut takes a function with one argument and one return value that can throw try.* error and returns a function that returns (value, error) in a regular Go style.

func Handle

func Handle(fn func(error), ws ...Wrapper)

Handle catches thrown errors, wraps them by wrappers (use Annotate here, if you need) and passed them to the fn function. Use Handle with defer (see examples of It/ItVal).

func HandleAs

func HandleAs(targetError *error, ws ...Wrapper)

HandleAs catches thrown errors, wraps them by wrappers (use Annotate here, if you need) and assigns them to the targetError. It is useful for functions that returns error. See example for use case.

Example
tryUnmarshal := func(data []byte) (result string, outErr error) {
	defer try.HandleAs(&outErr, try.Annotate("tryUnmarshal error: %w"))

	try.It(json.Unmarshal(data, &result))
	return
}

_, err := (tryUnmarshal([]byte(`Bad JSON`)))
fmt.Println(err)
Output:

tryUnmarshal error: invalid character 'B' looking for beginning of value

func It

func It(err error)

It is a high-level function that just throws error if passed err is not nil. It is useful for functions that returns error as a single value.

Example
defer try.Handle(func(err error) {
	fmt.Println("Oh,", err)
})

goodData := []byte(`"Good JSON"`)
badData := []byte(`Bad JSON`)
value := ""

try.It(json.Unmarshal(goodData, &value))
fmt.Println(value)

try.It(json.Unmarshal(badData, &value))
fmt.Println(value)
Output:

Good JSON
Oh, invalid character 'B' looking for beginning of value

func ItVal

func ItVal[T any](val T, err error) T

ItVal is a high-level function that throws error if passed err is not nil. If err is nil, it returns a passed val. It is useful for functions that returns two values: a result and an error.

Example
defer try.Handle(func(err error) {
	fmt.Println("Oh,", err)
})

goodValue := "Good value"
badValue := func() {} // functions cannot be serialized
var data []byte

data = try.ItVal(json.Marshal(goodValue))
fmt.Println(string(data))

data = try.ItVal(json.Marshal(badValue))
fmt.Println(string(data))
Output:

"Good value"
Oh, json: unsupported type: func()

func Throw

func Throw(err error)

Throw is an alias for It. It throws err if err is not nil. The 'throw' verb is more useful if you know exactly that err is not nil.

func Throwf added in v0.1.3

func Throwf(format string, args ...any)

Throwf allows to create and throw new error. Arguments are the same as for fmt.Errorf (and it is actually just a Throw(fmt.Errorf(...))).

func UnboxError

func UnboxError(val any) (error, bool)

UnboxError is a low-level function that checks the recover-ed value in panic handler, if it contains thrown error. If it does, UnboxError returns error and true. You don't need this function until you want to manually recover panics, thrown by this library.

Types

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result is a result of function response checking (see Check/CheckVal functions). It contains the return value and error.

func Check

func Check(err error) *Result[struct{}]

Check is an advanced version of It that returns Result value. Result allows to test/process error before throw.

func CheckVal

func CheckVal[T any](val T, err error) *Result[T]

CheckVal is an advanced version of ItVal that returns Result value. Result allows to test/process error before throw.

func (*Result[T]) Allow

func (r *Result[T]) Allow(errs ...error) (T, error)

Allow checks if the Result's error is (as in errors.Is) any of the given errs. If it is, the Result value and error is returned, else the error is thrown.

func (*Result[T]) AllowAs added in v0.1.5

func (r *Result[T]) AllowAs(target any) (T, error)

AllowAs checks the Result's error as (as in errors.As) the given target. If it is, the Result value and error is returned, else the error is thrown.

func (*Result[T]) AllowAsOr added in v0.1.5

func (r *Result[T]) AllowAsOr(target any) *Result[T]

AllowAsOr checks the Result's error as (as in errors.As) the given target. If it is, the Result is returned, else the error is thrown.

func (*Result[T]) AllowOr

func (r *Result[T]) AllowOr(errs ...error) *Result[T]

AllowOr checks if the Result's error is (as in errors.Is) any of the given errs. If it is, the Result is returned, else the error is thrown.

func (*Result[T]) Annotate

func (r *Result[T]) Annotate(format string, args ...any) T

Annotate wraps the Result's error with the custom message using fmt.Errorf and throws it.

The last placeholder of format string must be %w. The error passed to wrapper is appended to the end of the args list.

r.Annotate(...) is equivalent of r.Wrap(Annotate(...))

func (*Result[T]) Err

func (r *Result[T]) Err() error

Err returns error contained in Result.

func (*Result[T]) Val

func (r *Result[T]) Val() T

Val returns value contained in Result.

func (*Result[T]) Wrap

func (r *Result[T]) Wrap(ws ...Wrapper) T

Wrap wraps (and then throws) Result's error by the given wrappers. If error is nil, it returns Result value instead.

func (*Result[T]) WrapOr

func (r *Result[T]) WrapOr(ws ...Wrapper) *Result[T]

WrapOr wraps Result's error (if it isn't nil) by the given wrappers, and returns new Result with the same value and wrapped error.

type Wrapper

type Wrapper func(error) error

Wrapper describes function that processes (wraps) error into another form.

func Annotate

func Annotate(format string, args ...any) Wrapper

Annotate is a Wrapper that wraps the given error with the custom message using fmt.Errorf. The last placeholder of format string must be %w. The error passed to wrapper is appended to the end of the args list.

Jump to

Keyboard shortcuts

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