Skip to content

Instantly share code, notes, and snippets.

@a3s7p
Created November 23, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a3s7p/b2eb9dc1233b2ae9c4bcf005fe68305b to your computer and use it in GitHub Desktop.
Save a3s7p/b2eb9dc1233b2ae9c4bcf005fe68305b to your computer and use it in GitHub Desktop.
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