Created
October 4, 2018 00:07
-
-
Save ianfoo/e0441cb0be1c3560965c46acb4bf9d77 to your computer and use it in GitHub Desktop.
Example of an error list in Go. https://play.golang.org/p/MLWS5UhxI11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"strings" | |
) | |
type ErrorList []error | |
func (el ErrorList) Error() string { | |
s := make([]string, 0, len(el)) | |
for _, e := range el { | |
s = append(s, e.Error()) | |
} | |
return strings.Join(s, ", ") | |
} | |
func main() { | |
err := validate() | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
func validate() error { | |
var errList ErrorList | |
if err := subValidate("field"); err != nil { | |
errList = append(errList, err) | |
} | |
if err := subValidate("value"); err != nil { | |
errList = append(errList, err) | |
} | |
return errList | |
} | |
func subValidate(ctx string) error { | |
var errList ErrorList | |
for i := 0; i < 30; i++ { | |
if err := maybeError(ctx, i); err != nil { | |
errList = append(errList, err) | |
} | |
} | |
return errList | |
} | |
func maybeError(ctx string, i int) error { | |
if rand.Intn(3) == 1 { | |
return fmt.Errorf("invalid %s %d", ctx, i) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment