Created
March 7, 2016 11:32
-
-
Save mertenvg/1dfb7f79af55225e8041 to your computer and use it in GitHub Desktop.
Another (simpler) example using a task list to handle errors
This file contains hidden or 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" | |
"fmt" | |
) | |
// Task represents a callable task to be executed | |
type Task func() error | |
// Work slice of consecutive tasks that each may or may not have a single point of failure | |
type Work []Task | |
// Add a Task to the work queue | |
func (w *Work) Add(ts ...Task) { | |
*w = append(*w, ts...) | |
} | |
// Do the work | |
func (w Work) Do() (err error) { | |
for _, t := range w { | |
err = t() | |
if err != nil { | |
return | |
} | |
} | |
return | |
} | |
func main() { | |
work := Work{} | |
// task A | |
work.Add(func() (err error) { | |
fmt.Println("A") | |
return | |
}) | |
// task B | |
work.Add(func() (err error) { | |
fmt.Println("B") | |
return | |
}) | |
// task C | |
work.Add(func() (err error) { | |
fmt.Println("C") | |
err = errors.New("I don't know why, but Fail!") | |
return | |
}) | |
// task D | |
work.Add(func() (err error) { | |
fmt.Println("D") | |
return | |
}) | |
err := work.Do() | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
} | |
// Add link play.golang.org here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment