您可以在以下函数中提取恢复逻辑:
func recoverer(maxPanics, id int, f func()) { defer func() { if err := recover(); err != nil { fmt.Println("HERE", id) fmt.Println(err) if maxPanics == 0 { panic("TOO MANY PANICS") } else { go recoverer(maxPanics-1, id, f) } } }() f() }
然后使用它像:
go recoverer(5, 1, func() { printer(1, c) })