Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,32 @@ fmt.Println(cause) => password mismatch

```

## Working with [Errors](https://blog.golang.org/go1.13-errors) package

How to raise an `ApplicationError` with predefined error variables?

```
var ErrInvalidFormat = errors.New("[conf]invalid format")

func ReadConfig() (*Config,error) {
//...
return nil, Throw(ErrInvalidFormat, cfgFile)

}

func main() {

cfg, err := ReadConfig()

if errors.Is(err, ErrInvalidFormat) {
panic(err)
}

}

```

See [Unit Tests](throw_test.go) for more examples.



50 changes: 50 additions & 0 deletions throw.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package errors

import "strings"

// ApplicationError an appliction error with predifined error variable and detail message
type ApplicationError struct {
// Inner inner error
Inner error
// MsgList detail message
MsgList []string
}

// Error implement error.Error
func (e *ApplicationError) Error() string {
if e == nil {
return ""
}

if e.Inner != nil && e.MsgList != nil {
return e.Inner.Error() + ": " + strings.Join(e.MsgList, " ")
} else if e.Inner != nil {
return e.Inner.Error()
} else {
return strings.Join(e.MsgList, " ")
}

}

// Unwrap implement error.Unwrap
func (e *ApplicationError) Unwrap() error {
if e == nil {
return nil
}

if e.Inner != nil {
return e.Inner
}

return e
}

// Throw create an application error with prefinded error variable and message
// example
// errors.Throw(ErrInvalidParameter, "bloober_id is missing")
func Throw(inner error, msgList ...string) error {
return &ApplicationError{
Inner: inner,
MsgList: msgList,
}
}
40 changes: 40 additions & 0 deletions throw_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package errors

import (
"errors"
"testing"

"github.com/stretchr/testify/require"
)

func TestThrowIs(t *testing.T) {

errIs := errors.New("Is")

errIsNot := errors.New("Is not")

err := Throw(errIs, "", "errors.Is works")

require.ErrorIs(t, err, errIs)
require.Equal(t, false, errors.Is(err, errIsNot))
}

func TestThrowUnwrap(t *testing.T) {

inner := errors.New("Inner")

err := Throw(inner, "errors.Unwrap works")

require.Equal(t, inner, errors.Unwrap(err))
}

func TestThrowAs(t *testing.T) {

inner := errors.New("Inner")

err := Throw(inner, "errors.As works")

var appErr *ApplicationError

require.Equal(t, true, errors.As(err, &appErr))
}