github.com/seeker-insurance/kit@v0.0.13/errorlib/errorlib.go (about) 1 //Package errorlib contains tools to deal with errors, including the heavily-used `ErrorString` type (for errors that are compile-time constants) and `LoggedChannel` function (to report non-fatal errors during concurrent execution) 2 package errorlib 3 4 import ( 5 "errors" 6 7 "github.com/seeker-insurance/kit/log" 8 ) 9 10 //ErrorString is a string with an Error() method. This lets you declare errors as visible compile-time constants, 11 //which facilitates various IDE tools. 12 type ErrorString string 13 14 func (err ErrorString) Error() string { 15 return string(err) 16 } 17 18 const someErr ErrorString = "foo" 19 20 var _ error = someErr //satisfies interface 21 22 //LoggedChannel creates an error channel that will automatically log errors sent to it to the logger specified in kit/log. 23 func LoggedChannel() chan error { 24 errors := make(chan error) 25 go logErrors(errors) 26 return errors 27 } 28 29 //logErrors logs errors as they come in to os.stdout. 30 //Goroutine. Do not run directly! 31 func logErrors(errors <-chan error) { 32 for err := range errors { 33 log.Print(err) 34 } 35 } 36 37 //Errors is the default error channel used by functions in this package. 38 var Errors = make(chan error) 39 40 //Flatten a slice of errors into a single error 41 func Flatten(errs []error) error { 42 switch len(errs) { 43 case 0: 44 return nil 45 case 1: 46 return errs[0] 47 default: 48 errmsg := "multiple errors:" 49 for _, err := range errs { 50 errmsg += err.Error() 51 } 52 return errors.New(errmsg) 53 } 54 }