Created
September 12, 2014 09:45
-
-
Save cfstras/4294f58e310daeead09c to your computer and use it in GitHub Desktop.
Panic & Recover for long fail-fast methods
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" | |
"fmt" | |
"math/rand" | |
"runtime" | |
"time" | |
) | |
func main() { | |
rand.Seed(time.Now().Unix()) | |
err := doStuff() | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
func doStuff() (err error) { | |
defer func() { | |
if r := recover(); r != nil { | |
if _, ok := r.(runtime.Error); ok { | |
panic(ok) | |
} | |
err = r.(error) | |
} | |
}() | |
p := func(status string, err error) { | |
if err != nil { | |
panic(errors.New("Error " + status + ": " + err.Error())) | |
} | |
} | |
p("reticulating splines", reticulateSplines()) | |
p("reticulating more splines", reticulateSplines()) | |
spline1, err := getReticulatedSplines() | |
p("getting reticulated splines", err) | |
spline2, err := getReticulatedSplines() | |
p("getting more reticulated splines", err) | |
fmt.Println("Finished! Splines returned:", spline1, "and", spline2) | |
return nil | |
} | |
func reticulateSplines() error { | |
if rand.Intn(10) > 7 { | |
return errors.New("Not enough splines to reticulate!") | |
} | |
return nil | |
} | |
func getReticulatedSplines() (spline string, err error) { | |
if rand.Intn(10) > 7 { | |
return "", errors.New("No splines left to eat!") | |
} | |
return fmt.Sprint("spline number ", rand.Intn(10)), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: Running this on the playground will always create the same result, because time is frozen there.