Skip to content

Commit

Permalink
added ErrorString and MultiError
Browse files Browse the repository at this point in the history
  • Loading branch information
OneOfOne committed Sep 6, 2014
1 parent 918ad6c commit db5002c
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions errors/multierror.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package errors

import (
"bytes"
"fmt"
)

type ErrorString string

func (es ErrorString) Error() string {
return string(es)
}

type MultiError struct {
Errors []error
}

func (me *MultiError) Append(err interface{}) (added bool) {
added = true
switch err := err.(type) {
case error:
me.Errors = append(me.Errors, err)
case string:
me.Errors = append(me.Errors, ErrorString(err))
case []byte:
me.Errors = append(me.Errors, ErrorString(err))
case *MultiError:
me.Errors = append(me.Errors, err.Errors...)
case MultiError:
me.Errors = append(me.Errors, err.Errors...)
case []error:
me.Errors = append(me.Errors, err...)
case nil:
added = false
default:
added = false
}
return
}

func (me *MultiError) Len() int {
return len(me.Errors)
}

func (me *MultiError) Error() string {
if len(me.Errors) == 1 {
return me.Errors[0].Error()
}

buf := &bytes.Buffer{}
buf.WriteString("Multiple Errors Found:\n")
for i, e := range me.Errors {
fmt.Fprintf(buf, "\t[%d] %s\n", i, e.Error())
}
return buf.String()[:buf.Len()-1] // skip the last \n
}

0 comments on commit db5002c

Please sign in to comment.