Last active
July 11, 2019 06:54
-
-
Save xin053/e468ea08f9739496d3b076dddb5e0248 to your computer and use it in GitHub Desktop.
[go recover] go recover #go #recover
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
func Parse(input string) (s *Syntax, err error) { | |
defer func() { | |
if p := recover(); p!= nil { | |
err = fmt.Errorf("internal error: %v", p) | |
} | |
}() | |
} |
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
// 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