Skip to content

Instantly share code, notes, and snippets.

@qrntz qrntz/error.go
Created Nov 23, 2019

Embed
What would you like to do?
go error monad
package main
import (
"errors"
"log"
)
type F func() error
func errCompose(pipeline ...F) (e error, ok bool) {
ok = true
for _, f := range pipeline {
e = f()
if e != nil {
ok = false
break
}
}
return
}
func main() {
good := func() error {
log.Println("good function called")
return nil
}
good2 := func() error {
log.Println("good function 2 called")
return nil
}
bad := func() error {
log.Println("bad function called")
return errors.New("bad function returned error")
}
// if pipeline succeeds, handler does not get called
if _, ok := errCompose(good, good, good); !ok {
log.Println("this shouldn't happen")
}
// pipeline interrupts at first error
if e, ok := errCompose(good, bad, good2); !ok {
log.Println("good2 was not called:", e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.