Skip to content

Instantly share code, notes, and snippets.

@xin053
Last active July 11, 2019 06:54
Show Gist options
  • Save xin053/e468ea08f9739496d3b076dddb5e0248 to your computer and use it in GitHub Desktop.
Save xin053/e468ea08f9739496d3b076dddb5e0248 to your computer and use it in GitHub Desktop.
[go recover] go recover #go #recover
func Parse(input string) (s *Syntax, err error) {
defer func() {
if p := recover(); p!= nil {
err = fmt.Errorf("internal error: %v", p)
}
}()
}
// Automatically Restart a Crashed Goroutine
package main
import "log"
import "time"
func shouldNotExit() {
for {
// Simulate a workload.
time.Sleep(time.Second)
// Simulate an unexpected panic.
if time.Now().UnixNano() & 0x3 == 0 {
panic("unexpected situation")
}
}
}
func NeverExit(name string, f func()) {
defer func() {
if v := recover(); v != nil {
// A panic is detected.
log.Println(name, "is crashed. Restart it now.")
go NeverExit(name, f) // restart
}
}()
f()
}
func main() {
log.SetFlags(0)
go NeverExit("job#A", shouldNotExit)
go NeverExit("job#B", shouldNotExit)
select{} // block here for ever
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment