← All Exercises
Recover Panics in a Worker
advancedgo
Background
A panic unwinds the goroutine and, if unrecovered, terminates the process; libraries that call user code often recover at the boundary and convert it to an error.
Problem
Implement runSafely(fn func() error) (err error) that recovers any panic and returns an error containing the panic value. Then implement runJobs(count int) []string that runs count jobs, panics on index 1, and records ok or the recovered error for each job in order.
Input
A function that may panic and a number of simulated jobs.
Output
For each job in order, ok or an error string containing the recovered panic value.
Sample tests
Sample 1
Input: count = 3, job index 1 panics with "bad job"
Expected: ["ok", "panic recovered: bad job", "ok"]
Sample 2
Input: count = 0
Expected: []
Your solution
Learning objective
Place recover at a job boundary and preserve the panic value as an ordinary error.