Created
November 23, 2019 16:38
-
-
Save a3s7p/b2eb9dc1233b2ae9c4bcf005fe68305b to your computer and use it in GitHub Desktop.
go error monad
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 ( | |
"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