Skip to content

Commit

Permalink
Merge 12bd6d1 into bbf6a5b
Browse files Browse the repository at this point in the history
  • Loading branch information
donutloop committed Dec 22, 2017
2 parents bbf6a5b + 12bd6d1 commit fb25b24
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 0 deletions.
21 changes: 21 additions & 0 deletions multierror/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Usage

MultiError concatenate errors into one error.

## Example
```go
package main

import (
"github.com/donutloop/toolkit/multierror"
"fmt"
)

func main() {
errs := []error{
errors.New("error connect to db failed"),
errors.New("error marschaling json"),
}
fmt.Println(multierror.New(errs...))
}
```
18 changes: 18 additions & 0 deletions multierror/doc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package multierror_test

import (
"fmt"

"errors"

"github.com/donutloop/toolkit/multierror"
)

func ExampleMultiError() {
errs := []error{
errors.New("error connect to db failed"),
errors.New("error marschaling json"),
}
fmt.Println(multierror.New(errs...))
// Output: multiple errors: error connect to db failed; error marschaling json
}
44 changes: 44 additions & 0 deletions multierror/muliterror.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package multierror

import "bytes"

// New concatenate errors into one.
// If all errors are nil then it will returns nil
// otherwise the return value is a MultiError containing all the non-nil error.
func New(errs ...error) error {
if len(errs) == 0 {
return nil
}
errBucket := make([]error, 0, len(errs)/2)
for _, err := range errs {
if err != nil {
errBucket = append(errBucket, err)
}
}
if len(errBucket) == 0 {
return nil
}
return multiError{errBucket}
}

// MultiError concatenate errors into one error.
type multiError struct {
Errors []error
}

func (es multiError) Error() string {
switch len(es.Errors) {
case 1:
return es.Errors[0].Error()
default:
var buf bytes.Buffer
buf.WriteString("multiple errors: ")
for i, e := range es.Errors {
if i > 0 {
buf.WriteString("; ")
}
buf.WriteString(e.Error())
}
return buf.String()
}
}
22 changes: 22 additions & 0 deletions multierror/muliterror_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package multierror_test

import (
"errors"

"testing"

"github.com/donutloop/toolkit/multierror"
)

func TestMultiError_Error(t *testing.T) {
errs := []error{
nil,
errors.New("error connect to db failed"),
errors.New("error marschaling json"),
}
expectedValue := "multiple errors: error connect to db failed; error marschaling json"
err := multierror.New(errs...)
if err.Error() != expectedValue {
t.Errorf(`unexpected error message (actual:"%s", expected: "%s")`, err.Error(), expectedValue)
}
}

0 comments on commit fb25b24

Please sign in to comment.