Overview
Catch a panicking HTTP handler with defer and recover in Go and turn it into an error, so one bad request can't crash the whole server.
- defer runs when the function returns
- recover() stops a panic
- set a named result inside the deferred function
Short Course
defer runs a function when the surrounding one returns, even after a panic,
and recover() inside it stops the panic. Trap: recover works only when
called directly in a deferred function; anywhere else it returns nil.
func safe() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("caught: %v", r)
}
}()
panic("boom")
}
Task
Write Serve(handler func(int) int, n int) (result int, err error): return
handler(n), or if it panics, 0 and the error
"handler panicked: <value>". Example: a handler that panics with "db down"
→ 0, handler panicked: db down.
Test Suites
Pending
Next
Output