Skip to content

Instantly share code, notes, and snippets.

@cfstras
Created September 12, 2014 09:45
Show Gist options
  • Select an option

  • Save cfstras/4294f58e310daeead09c to your computer and use it in GitHub Desktop.

Select an option

Save cfstras/4294f58e310daeead09c to your computer and use it in GitHub Desktop.
Panic & Recover for long fail-fast methods
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
}
@cfstras

cfstras commented Sep 12, 2014

Copy link
Copy Markdown
Author

Note: Running this on the playground will always create the same result, because time is frozen there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment