A panic recovery pattern places deferred recovery around goroutine or request-handler work, records the panic, and lets the surrounding application continue running. section 4.3.5
Implement the pattern by:
- Starting the goroutine or handler inside a protected function. section 4.3.5
- Deferring an anonymous function that calls recover. section 4.3.5
- Logging or displaying the recovered panic information. section 4.3.5
- Deferring required cleanup, such as closing a network connection. section 4.3.5
Protecting a goroutine
A helper accepts a no-argument function, launches it in a goroutine, and recovers panics inside that goroutine. Calling it with a function that panics logs the error while the main program continues. section 4.3.5
Figure 4.2 A simple server
Use the server and goroutine listings to compare an unprotected panic with deferred recovery and logged continuation. section 4.3.5
