Skip to content

2rebi/werror

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

werror

Build Status GitHub release (latest by date) GitHub go.mod Go version license

wrap error

Install

go get github.com/rebirthlee/werror

Example

Simple

package main

import (
	"errors"
	"fmt"
	"github.com/rebirthlee/werror"
)

var (
	errNotFound = errors.New("not found")
	errComputeFailed = errors.New("compute failed")
)

func getOne() (int64, error) {
	// get success
	// return 1, nil
	
	// get failed
	return 0, errNotFound
}

func compute() error {
	res, err := getOne()
	if err != nil {
		return werror.Wrap(errComputeFailed, err)
	}
	
	res++ // compute dummy
	return nil
}

func main() {
	err := compute()
	
	// is
	fmt.Println(errors.Is(err, errNotFound)) // true
	fmt.Println(errors.Is(err, errComputeFailed)) // true
}

Advanced

package main

import (
	"errors"
	"fmt"
	"github.com/rebirthlee/werror"
)

type myNotFoundError struct { }

func (*myNotFoundError) Error() string {
	return "not found"
}

type myComputeError struct { }

func (*myComputeError) Error() string {
	return "compute failed"
}


var (
	errNotFound error = &myNotFoundError{}
	errComputeFailed error = &myComputeError{}
)

func getOne() (int64, error) {
	// get success
	// return 1, nil
	
	// get failed
	return 0, errNotFound
}

func compute() error {
	res, err := getOne()
	if err != nil {
		return werror.Wrap(errComputeFailed, err)
	}
	
	res++ // compute dummy
	return nil
}

func main() {
	err := compute()
	
	// is
	fmt.Println(errors.Is(err, errNotFound)) // true
	fmt.Println(errors.Is(err, errComputeFailed)) // true
	
	// get error
	fmt.Println(errors.Unwrap(err)) // "compute failed"
	
	// get cause
	fmt.Println(werror.Cause(err)) // "not found"
	
	// as
	var node *werror.ErrorNode
	fmt.Println(errors.As(err, &node)) // true
	
	var myError1 *myNotFoundError
	fmt.Println(errors.As(err, &myError1)) // true

	var myError2 *myComputeError
	fmt.Println(errors.As(err, &myError2)) // true
}

License

THE BEER-WARE LICENSE (Revision 42)