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 ¶
- func Handle(fn func(error), ws ...Wrapper)
- func HandleAs(targetError *error, ws ...Wrapper)
- func It(err error)
- func ItVal[T any](val T, err error) T
- func Throw(err error)
- func UnboxError(val any) (error, bool)
- type Result
- func (r *Result[T]) Allow(errs ...error) (T, error)
- func (r *Result[T]) AllowOr(errs ...error) *Result[T]
- func (r *Result[T]) Annotate(format string, args ...any) T
- func (r *Result[T]) Err() error
- func (r *Result[T]) Val() T
- func (r *Result[T]) Wrap(ws ...Wrapper) T
- func (r *Result[T]) WrapOr(ws ...Wrapper) *Result[T]
- type Wrapper
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func It ¶
func It(err error)
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/davidmz/try"
)
func main() {
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 ¶
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/davidmz/try"
)
func main() {
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 UnboxError ¶
Types ¶
Click to show internal directories.
Click to hide internal directories.